首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用Jest模拟React组件静态方法

如何用Jest模拟React组件静态方法
EN

Stack Overflow用户
提问于 2020-04-04 08:07:38
回答 1查看 974关注 0票数 2

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

代码语言:javascript
运行
复制
// YourComponent.js

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

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

export default YourComponent;
代码语言:javascript
运行
复制
// 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');
  });
});
EN

回答 1

Stack Overflow用户

发布于 2020-04-07 11:57:24

以下是解决方案:

index.js

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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');
  });
});

单元测试结果和覆盖率报告:

代码语言:javascript
运行
复制
 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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61022182

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档