i am trying to write tests using jest the integration is a call that have a private function called test- gets called by funcTest trying to mock implementation in before each how ever the mock does not work and it goes to the real function "test". when i put the assignment (integration['test']=mockFn;) inside the "it" it works perfectly . example for working code:
describe('test', () => {
const mockFn: jest.Mock = jest.fn();
beforeEach(async () => {
const integration = new integrationTest();
})
afterEach(() => {
jest.restoreAllMocks();
});
it('call mock implemntaion', async () => {
integration['test']=mockFn;
mockFn.mockImplementation(() => {
throw new Error('error');
});
try {
await integration.funcTest();
} catch (e) {
expect(e).toBeInstanceOf(Error);
}
});
})
example of not working code:
describe('test', () => {
const mockFn: jest.Mock = jest.fn();
beforeEach(async () => {
const integration = new integrationTest();
integration['test']=mockFn;
})
afterEach(() => {
jest.restoreAllMocks();
});
it('call mock implemntaion', async () => {
mockFn.mockImplementation(() => {
throw new Error('error');
});
try {
await integration.funcTest();
} catch (e) {
expect(e).toBeInstanceOf(Error);
}
});
})
why does this happen and how to fix thanks