如何用笑话模拟React Component静态方法

问题描述 投票:0回答:1

这真的很难找出方法。我找不到任何代码来展示如何在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');
  });
});
reactjs mocking jestjs static-methods react-component
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.