Bill Tran
Bill Tran

Reputation: 21

How to mock a React Component static method with Jest

This was really hard to find out how to do. I could not find any code to show you how to mock a static method in a React Component. This way worked for me.

// YourComponent.js

class YourComponent extends Component {
  static getHelloWorld () {
    return 'hello world';
  }

  render() {
    return (
      <div>{YourComponent.getHelloWorld()}</div>
    )
  }
}

export default YourComponent;
// YourComponent.test.js
import { mount } from 'enzyme';
import YourComponent from './YourComponent';

YourComponent.__proto__.getHelloWorld = jest.fn(() => { return 'Hello Universe' });

describe('YourComponent test for mocking static method', () => {
  it('should render', () => {
    const wrapper = mount(<YourComponent />);

    expect(wrapper.text()).toEqual('Hello Universe');
  });
});

Upvotes: 2

Views: 2063

Answers (1)

Lin Du
Lin Du

Reputation: 102297

Here is the solution:

index.js:

import { Component } from 'react';

class YourComponent extends Component {
  static getHelloWorld() {
    return 'hello world';
  }

  render() {
    return <div>{YourComponent.getHelloWorld()}</div>;
  }
}

export default YourComponent;

index.test.js:

import { mount } from 'enzyme';
import YourComponent from './';

describe('YourComponent test for mocking static method', () => {
  it('should render', () => {
    YourComponent.getHelloWorld = jest.fn(() => {
      return 'Hello Universe';
    });
    const wrapper = mount(<YourComponent />);

    expect(wrapper.text()).toEqual('Hello Universe');
  });
});

unit test result with coverage report:

 PASS  stackoverflow/61022182/index.test.js (8.455s)
  YourComponent test for mocking static method
    ✓ should render (30ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   88.89 |      100 |   66.67 |    87.5 |                   
 index.js |   88.89 |      100 |   66.67 |    87.5 | 5                 
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.327s

Upvotes: 2

Related Questions