简体   繁体   中英

Jest mock not being used when called from a constant being imported from another file

I have a method which is using a constant defined in another call. This constant in itself makes a service call that I have mocked. When resolving this constant from the other file the mocked function is not being called

//function i am trying in test.ts
export const testableFunction = async() => {
  return EXPORTED_CONSTANT
}

//constant being exported from constants.ts
export const EXPORTED_CONSTANT = {
  value : service.method()
}

// unit test I have written
it('message trigger for sendInteractiveWhatsapp', async () => {
  jest.spyOn(service, 'method').mockImplementation(async () => {
     return "some_value";
  });
  expect(await testableFunction()).toEqual({value: 'some_value'});
});

This test is failing because the mock value being return is undefined. ie {}:= {value: 'some_value'}

You can try mocking the constants.ts file at the top of your tests. That way you will be mocking any uses of that module and its contents while your tests run. Following is a sample from jest documentation.

import moduleName, {foo} from '../moduleName';

jest.mock('../moduleName', () => {
  return {
    __esModule: true,
    default: jest.fn(() => 42),
    foo: jest.fn(() => 43),
  };
});

moduleName(); // Will return 42
foo(); // Will return 43

You can read more about different types of mocks here

Your method in service is async, then you needs resolve into "EXPORTED_CONSTANT".

example:

export const testableFunction = async () => {
  return EXPORTED_CONSTANT();
};

//constant being exported from constants.ts
export const EXPORTED_CONSTANT = async () => ({
  value: await service.method(),
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM