Вы можете использовать jest.mock (moduleName, factory, options) для макета myHelper
модуля и myHelper
функции.
Например myService.js
:
import { myHelper } from './myHelper';
export class MyService {
myMethod() {
const myVar = myHelper(42);
return myVar;
}
}
myHelper.js
:
export function myHelper(n) {
return n;
}
myService.test.js
:
import { MyService } from './myService';
import { myHelper } from './myHelper';
jest.mock('./myHelper', () => {
return {
myHelper: jest.fn(),
};
});
describe('my test', () => {
it('should work properly', () => {
myHelper.mockReturnValueOnce(24);
const myService = new MyService();
expect(myService.myMethod()).toBe(24);
});
});
Результаты модульного теста со 100% покрытием:
PASS stackoverflow/61370607/myService.test.js (13.137s)
my test
✓ should work properly (3ms)
--------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
myService.js | 100 | 100 | 100 | 100 |
--------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.028s
исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61370607