mikasa
mikasa

Reputation: 900

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?

Upvotes: 0

Views: 562

Answers (1)

Lin Du
Lin Du

Reputation: 102267

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

Upvotes: 1

Related Questions