【问题标题】:JEST services mocking not working properlyJEST 服务模拟无法正常工作
【发布时间】:2021-06-29 04:49:08
【问题描述】:

我们正在添加一个测试用例以在调用 test() 时检查 testPromiseFlag 和 testCallbackFlag 是否为真。

//test.vue
testPromiseFlag = false;
testCallbackFlag = false;

        promiseTester() {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve();
                }, 2000)
            })
        }

        callbackTester(cb) {
            return cb();
        }

        test(): void {
            this.promiseTester().then(() => {
                this.testPromiseFlag = true;
            });
            this.callbackTester(() => {
                this.testCallbackFlag = true;
            })
        }

测试文件包含如下:

//test.jest.ts
import { shallowMount, createLocalVue, config } from '@vue/test-utils'
import Vuex from 'vuex'
import test from './test.vue';
let localVue = createLocalVue();
localVue.use(Vuex);

describe('test', () => {
    let wrapper: any;
    let instance: any;

    beforeEach(() => {
        wrapper = shallowMount(test, {});
        instance = wrapper.vm;
    });

    test('should testPromiseFlag and testCallbackFlag be true', async () => {
        await instance.test();
        await wrapper.vm.$nextTick();
        expect(instance.$data.testPromiseFlag).toBeTruthy();
        expect(instance.$data.testCallbackFlag).toBeTruthy();
        wrapper.destroy();
    });
});

运行测试用例后,我们收到“expect(received).toBeTruthy() Received: false”。 有解决这个问题的办法吗?

【问题讨论】:

    标签: vue.js jestjs vue-test-utils


    【解决方案1】:

    test() 应该返回一个Promise。否则await 会立即解析。

    解决此问题的一种方法是使test() 成为async 函数(有效地返回Promise),awaits promiseTester()

    async test() {
      await this.promiseTester();
      this.testPromiseFlag = true;
      this.callbackTester(/*...*/); 
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 2020-08-14
      • 2015-09-27
      相关资源
      最近更新 更多