Вы можете использовать jest.spyOn (object, methodName) метод, здесь завершена демонстрация:
idnex.tsx
:
import React, { Component } from 'react';
import { someHelper } from './utils';
class SomeComponent extends Component {
render() {
return <div>some component, {someHelper()}</div>;
}
}
export default SomeComponent;
utils.ts
:
export const someHelper = () => 'return value';
index.spec.tsx
:
import React from 'react';
import SomeComponent from './index';
import * as utils from './utils';
import { shallow } from 'enzyme';
describe('SomeComponent', () => {
beforeEach(() => {
jest.restoreAllMocks();
});
test('should mock utils', () => {
const someHelperSpy = jest.spyOn(utils, 'someHelper').mockReturnValue('mocked return value');
const wrapper = shallow(<SomeComponent></SomeComponent>);
expect(jest.isMockFunction(utils.someHelper)).toBeTruthy();
expect(wrapper.text()).toBe('some component, mocked return value');
expect(someHelperSpy).toBeCalled();
});
});
Результат модульного теста с отчетом о покрытии:
PASS src/stackoverflow/58521281/index.spec.tsx
SomeComponent
✓ should mock utils (11ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 90 | 100 | 66.67 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
utils.ts | 50 | 100 | 0 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 7.589s, estimated 14s
Исходный код: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58521281