Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用Jest模拟VueJS组件中的自定义模块_Node.js_Typescript_Vue.js_Vuejs2_Jestjs - Fatal编程技术网

Node.js 使用Jest模拟VueJS组件中的自定义模块

Node.js 使用Jest模拟VueJS组件中的自定义模块,node.js,typescript,vue.js,vuejs2,jestjs,Node.js,Typescript,Vue.js,Vuejs2,Jestjs,我正试图在我的一个Vue组件上编写一个简单的Jest单元测试 技术堆栈:TypeScript、VueJS、Jest、Webpack、 结构: root - src - invite - accept.ts - accept.vue - test - invite - accept.ts - app.ts - jest.config.json - package.json import Vue from "

我正试图在我的一个Vue组件上编写一个简单的Jest单元测试

技术堆栈:TypeScript、VueJS、Jest、Webpack、

结构

 root
   - src
     - invite
      - accept.ts
      - accept.vue
   - test
     - invite
       - accept.ts
   - app.ts
   - jest.config.json
   - package.json
import Vue from "vue";
import Component from 'vue-class-component';
import { eventBus } from './../app';

@Component
export default class InviteAccept extends Vue {

    created() {
        console.log(eventBus);
        eventBus.$emit('hideNavigation');
    };
}
在尝试使用Jest模拟依赖模块时,我观察到一些奇怪的行为

src/invite/accept.ts

 root
   - src
     - invite
      - accept.ts
      - accept.vue
   - test
     - invite
       - accept.ts
   - app.ts
   - jest.config.json
   - package.json
import Vue from "vue";
import Component from 'vue-class-component';
import { eventBus } from './../app';

@Component
export default class InviteAccept extends Vue {

    created() {
        console.log(eventBus);
        eventBus.$emit('hideNavigation');
    };
}
src/invite/accept.vue

<template>
    <div class="row">
        <div class="col">
            <h1>Blah</h1>
        </div>
    </div>
</template>
<script src="./accept.ts" lang="ts"></script>
/jest.config.json

{
  "transform": {
    "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js",
    "\\.(vue)$": "<rootDir>/node_modules/vue-jest"
  },
  "testRegex": "/test/.*\\.(ts|tsx)$",
  "moduleFileExtensions": [
    "vue",
    "ts",
    "tsx",
    "js"
  ],
  "transformIgnorePatterns": [
    "<rootDir>/node_modules/(?!lodash-es/.*)"
  ]
}
{
  "name": "blah",
  "version": "1.0.0",
  "license": "UNLICENSED",
  "scripts": {
    "build": "webpack --config webpack.prod.js",
    "watch": "webpack --watch --config webpack.dev.js",
    "test": "jest -c jest.config.json"
  },
  "devDependencies": {
    "@types/es6-promise": "^3.3.0",
    "@types/jest": "^22.2.3",
    "@vue/test-utils": "^1.0.0-beta.16",
    "applicationinsights-js": "^1.0.15",
    "bootstrap-vue": "^2.0.0-rc.9",
    "clean-webpack-plugin": "^0.1.19",
    "css-loader": "^0.28.10",
    "es6-promise": "^4.2.4",
    "extract-text-webpack-plugin": "3.0.2",
    "html-webpack-plugin": "^3.0.6",
    "jest": "^22.4.3",
    "jest-teamcity-reporter": "^0.9.0",
    "ts-jest": "^22.4.6",
    "ts-loader": "3.4.0",
    "typescript": "^2.7.2",
    "vue": "^2.5.13",
    "vue-class-component": "^6.2.0",
    "vue-jest": "^2.5.0",
    "vue-loader": "^14.1.1",
    "vue-router": "^3.0.1",
    "vue-style-loader": "^4.0.2",
    "vue-template-compiler": "^2.5.13",
    "vue-types": "^1.2.0",
    "webpack": "3.10.0",
    "webpack-merge": "^4.1.2"
  },
  "dependencies": {}
}
最后是测试类

/test/invite/accept.ts

import { polyfill } from 'es6-promise'
import Vue from 'vue';
import VueRouter from 'vue-router';
import Invite from './invite/accept.vue';

polyfill();

export const eventBus = new Vue();

const router = new VueRouter({
    routes: [
        { path: '/invite/accept/:token', component: Invite, name: 'inviteAccept' },
        { path: '/', component: undefined, name: 'index' },
    ]
});

Vue.use(VueRouter);

const app = new Vue({ router }).$mount('#app');
import InviteAccept from './../../src/invite/accept';
import { eventBus } from './../../src/app';
import { shallowMount, createLocalVue } from '@vue/test-utils';
import VueRouter = require('vue-router'); // This needs to be 'require', rather than 'from'. Some weird thing or something.
import 'jest';

describe('invites', () => {
    jest.mock('./../../src/app', () => 'anything');

    function createWrapper() {
        const localVue = createLocalVue();
        localVue.use(VueRouter);
        const router = new VueRouter();

        return shallowMount(InviteAccept, {
            localVue,
            router
        });
    };

    test('should mock in test', () => {
        // this works:
        const test = require('./../../src/app');
        expect(test).toEqual('anything');
    });

    test('should mock in component', () => {
        const wrapper = createWrapper();
    });

});
名为
的测试应在测试中模拟
获取
事件总线的模拟值并通过

名为
应在组件中模拟的测试
没有获得
事件总线
的模拟值,它是
未定义的
。准确的误差如下:

TypeError: Cannot read property '$emit' of undefined

      at VueComponent.Object.<anonymous>.InviteAccept.created (src/invite/accept.vue:49:23)
      at callHook (node_modules/vue/dist/vue.runtime.common.js:2919:21)
      at VueComponent.Vue._init (node_modules/vue/dist/vue.runtime.common.js:4628:5)
      at new VueComponent (node_modules/vue/dist/vue.runtime.common.js:4796:12)
      at createInstance (node_modules/@vue/test-utils/dist/vue-test-utils.js:4230:12)
      at mount (node_modules/@vue/test-utils/dist/vue-test-utils.js:5376:12)
      at Object.shallowMount (node_modules/@vue/test-utils/dist/vue-test-utils.js:5414:10)
      at createWrapper (test/invite/accept.ts:13:29)
      at Object.<anonymous> (test/invite/accept.ts:25:23)
TypeError:无法读取未定义的属性“$emit”
在VueComponent.Object。)关于自动模拟,我认为上面的说法是正确的

我肯定我遗漏了一些明显的东西,但我不知道是什么。任何帮助都将不胜感激:-)

jest.mock(“../../../src/app”“,()=>“任何东西”)
mocks模块导出时带有工厂函数返回的值:

    const test = require('./../../src/app');
    expect(test).toEqual('anything');
虽然这将适用于ES模块导入,因为它们在内部使用CommonJS模块,但这是违反规范的,因为导入应该是一个对象

在测试中调用的测试应该模拟获取eventBus的模拟值并通过

它不会被模拟
eventBus
。它获得导出

在组件中调用的测试应模拟未获得eventBus的模拟值

“anything”字符串上没有
eventBus
属性,这就是测试失败的原因

应使用以下命令模拟命名导出:

jest.mock('./../../src/app', () => ({
  eventBus: { $emit: jest.fn() }
}));

太棒了,真管用!它只是有点违背了我自己关于模拟框架应该如何运行的直觉。很好的解释!很高兴这有帮助。