So, I have two methods on a Node project:
export function methodA() {
const response = await methodB();
return response.length ? 'something' : 'else';
}
export function methodB() {
const array = await getData(); // Access database and make API calls
return array[];
}
methodA
calls methodB
and methodB
makes stuff that I don't care right now for my unit testing purposes, so I want to mock methodB
so it will return an empty array and won't try to make any database or API calls. The issue is that I can't actually mock methodB
, as my test is still calling the actual function.
Here's my test:
describe('method testing', () => {
it('calls method', async () => {
const response = await myModule.methodA();
expect(response).toBe('else');
});
});
That test is failing, because jest is still calling the actual methodB
which is meant to fail, as it can't connect to the database or reach APIs, so, this is what I tried doing to mock methodB
:
Spying on the method:
import * as myModule from '@/domains/methods';
jest.spyOn(myModule, 'methodB').mockImplementation(() => [] as any);
// describe('method testing', () => {...
Mocking the entire file except for the methodA
:
jest.mock('@/domains/methods', () => {
const originalModule = jest.requireActual('@/domains/methods')
return {
...originalModule,
methodB: jest.fn().mockReturnValue([])
}
});
// describe('method testing', () => {...
I have also tried:
- Mocking
methodB
inside each test and insidedescribe
- Spying
methodB
inside each test and insidedescribe
- Some variations of those examples I wrote above
I'm not entirely sure on what to do right now, so any light would be appreciated.
@Update: Altough the problem is similar, this is not a duplicate question and this (How to mock functions in the same module using Jest?) does not answer my question.