reactjs - 如何在 Jest 中模拟变量?
问题描述
Foo.jsx
import React from 'react';
export default (props) => {
let {val} = props;
if (val) {
return 'ReactComponentFail';
} else {
return 'ReactComponent';
}
};
Foo.test.js
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Foo from './Foo';
Enzyme.configure({ adapter: new Adapter() });
let wrapper;
describe('foo test', () => {
let props = { val: 0 }
wrapper = shallow(<Foo {...props} />);
test('component test', () => {
expect(wrapper.text()).toEqual('ReactComponent');
});
});
我怎么能嘲笑props
?所以,我可以获得 100% 的代码覆盖率,任何帮助将不胜感激。我在谷歌上找不到任何关于如何模拟道具的信息。
解决方案
创建模拟props
并将其传递给您的 SFC。
例如
foo.jsx
:
import React from 'react';
export default (props) => {
let { val } = props;
if (val) {
return 'ReactComponentFail';
} else {
return 'ReactComponent';
}
};
foo.test.jsx
:
import React from 'react';
import { shallow } from 'enzyme';
import Foo from './foo';
describe('foo test', () => {
test('should return ReactComponent', () => {
let props = { val: 0 };
let wrapper = shallow(<Foo {...props} />);
expect(wrapper.text()).toEqual('ReactComponent');
});
test('should return ReactComponentFail', () => {
let props = { val: 1 };
let wrapper = shallow(<Foo {...props} />);
expect(wrapper.text()).toEqual('ReactComponentFail');
});
});
覆盖率 100% 的单元测试结果:
PASS stackoverflow/62694921/foo.test.jsx (10.41s)
foo test
✓ should return ReactComponent (6ms)
✓ should return ReactComponentFail
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
foo.jsx | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 11.845s, estimated 12s
推荐阅读
- express - passport.authenticate 无法正常工作
- c++ - Chicken Egg Class Interface in C++
- r - 正则表达式编写您自己的 NGram 分词器
- python - Alembic:AttributeError:“RedshiftDDLCompiler”对象没有属性“访问子句”
- mysql - SQL OrderBy 子句不适用于最大别名
- reactjs - 如何在 MaterialUI 中从 Select 中更改 Menu 下拉元素?
- google-cloud-platform - GCP VPC 服务控制允许从 VM SSH 浏览器下载
- aws-api-gateway - API Gateway Lambda 代理和 Cognito
- r - 由于 CPL_write_ogr 错误,写入 sf 对象失败
- java - 重构在矩阵中给出最大路径和的路径