gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:17:11 24 4
gpt4 key购买 nike

这真的很难找到怎么做。我找不到任何代码来向您展示如何在 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');
});
});

最佳答案

这是解决方案:
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

关于reactjs - 如何使用 Jest 模拟 React Component 静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61022182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com