reactjs - 如何使用 Enzyme 和 Jest 创建组件的浅渲染?
问题描述
我正在尝试尽我所能遵循使用 Enzyme 和 Jest 创建浅层渲染的文档,但我似乎遗漏了一些东西。这是我的组件。
class Example extends Component {
constructor(props) {
super(props);
this.state = {
code: ""
}
}
getCode() {
return "7";
}
render() {
return (
<div></div>
);
}
}
export default Example;
当我在浅层渲染上调用 getCode() 时,我希望得到“7”,但渲染是未定义的。
这是我的测试用例:
import Example from './Example'
import { shallow } from 'enzyme';
it('gets a code from example', () => {
const component = shallow(<Example />);
console.log(JSON.stringify(component));
expect(component.getCode().toEqual('7'));
});
我的输出:
FAIL src/components/CreateGame/Example.test.js (8.116s)
● Console
console.log src/components/CreateGame/Example.test.js:7
{}
● gets a code from example
TypeError: component.getCode is not a function
7 | console.log(JSON.stringify(component));
8 |
> 9 | expect(component.getCode().toEqual('7'));
| ^
10 | });
at Object.<anonymous> (src/components/CreateGame/Example.test.js:9:20)
我觉得我可能在这里遗漏了一些小东西,但对于我的生活,我无法弄清楚它是什么。
解决方案
如果getCode
是组件内的方法,则必须获取instance
:
import Example from './Example'
import { shallow } from 'enzyme';
it('gets a code from example', () => {
const component = shallow(<Example />);
const instance = component.instance(); // This is missing
expect(instance.getCode().toEqual('7'));
});
推荐阅读
- azure - Azure 自动化 Runas 帐户权限不足
- c++ - 如何根据输入的特定分数打印学生记录
- python - Airflow Webserver 连接到错误的数据库?
- f# - Fable-Elmish - 使用 SAFE 堆栈正确处理 F# 中的表单
- swift - 共享表从一开始就没有打开
- elasticsearch - 对关键字聚合进行不区分大小写的排序。ES 7.7.0
- python - 如何在带有启动选项的沙盒中启动 Steam?
- laravel - Laravel:防止 Illuminate\Support\Arr::dot() 为一维数组项创建键
- c++ - 在执行期间用 std::bind 重新分配 std::function
- ssl - *.*.companyname.com SSL 证书,要求什么以及注意什么