user2845121
user2845121

Reputation: 113

JEST services mocking not working properly

We are adding a test case to check testPromiseFlag and testCallbackFlag true while test() gets called.

//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 file contain as below:

//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();
    });
});

After run testcase we are receiving "expect(received).toBeTruthy() Received: false". Any fix for this issue?

Upvotes: 1

Views: 450

Answers (1)

tony19
tony19

Reputation: 138196

test() should return a Promise. Otherwise await resolves immediately.

One way to fix this is to make test() an async function (which effectively returns a Promise) that awaits promiseTester():

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

Upvotes: 1

Related Questions