如何使用Jest模拟React Component静态方法

时间:2020-04-04 00:07:37

标签: reactjs mocking jestjs static-methods react-component

这真的很难找到怎么做。我找不到任何代码来展示如何在React Component中模拟静态方法。这种方式对我有用。

// 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');
  });
});

1 个答案:

答案 0 :(得分:0)

这是解决方案:

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

具有覆盖率报告的单元测试结果:

 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