As a newcomer to Jest, I am grappling with understanding the intricacies of this testing framework. My current conundrum revolves around comprehending the behavior of ES6 class mocking within asynchronous code. For instance, consider an exported class setup like this:
//util_tests.ts
export default class Utils{
getMemberAccounts = (): Promise<Number> => new Promise((resolve, reject) => resolve(5));
}
Next, let's examine the file we wish to test (with the targeted function being getMemberAccounts):
//test.ts
import Util from './util_test'
import logger from '../common/logger';
import _ from 'lodash';
const util = new Util();
util.getMemberAccounts().then(test =>{
logger.info(test); // this should display mocked data
});
setTimeout(async ()=> {
let test = await util.getMemberAccounts();
logger.info(test); // here the mocked data does not appear, why is that so? And how can we address this issue?
}, 0);
export default class Test{
}
The structure of my test file is as follows:
import Util from '../src/test/util_test'
import Test from '../src/test/test'
import { mocked } from 'ts-jest/utils'
jest.mock('../src/test/util_test', () => {
return jest.fn().mockImplementation(() => {
return {
getMemberAccounts: jest.fn().mockResolvedValue({
accounts: [
{
id: '0zh8ap6luxoijne8qlfu1sg',
name: 'test',
officeNumber: '23',
emailAddress: 'string@gmail'
}
]
}
)
};
});
});
describe('Test', () => {
let testCase: Test;
beforeEach(async () => {
mocked(Util).mockClear();
testCase = new Test();
})
test('test-case', async () => {
})
});
Why is it that my mocking setup fails to work within the setTimeout function? Could this be attributed to the nature of setTimeout and callbacks? How can I successfully mock the class function in such a scenario?