简体   繁体   中英

Jest - Mock a function getting imported in a component file you're testing

I have a class component that I want to test using jest. That component is using a function getting imported from a utils file. How do I mock that imported function from my main test file?

You can use jest.spyOn(object, methodName) method, here is a completed demo:

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();
  });
});

Unit test result with coverage report:

 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

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58521281

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM