【问题标题】:How to mock a React Component static method with Jest如何使用 Jest 模拟 React 组件静态方法
【发布时间】:2020-07-16 05:32:16
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    解决办法如下:

    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
    

    【讨论】:

      猜你喜欢
      • 2017-06-09
      • 2020-09-08
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      相关资源
      最近更新 更多