javascript - 使用钩子测试有状态的 React 组件时出现意外结果?(笑话)
问题描述
我是测试新手,创建具有计数器状态和 useState 反应钩子的简单组件,当单击按钮时增加计数器:
零件:
const Counter= () => {
const[counter, setCounter] = useState(0);
const handleClick=() => {
setCounter(counter + 1);
}
return (
<div>
<h2>{counter}</h2>
<button onClick={handleClick} id="button">increment</button>
</div>
)
}
Counter.test.js:
it('increment counter correctly', () => {
let wrapper = shallow(<Counter/>);
const counter = wrapper.find('h2');
const button = wrapper.find('button');
button.simulate('click')
console.log(counter.text()) // 0
})
counter.text()
模拟按钮单击打印0而不是1后记录;当我试图监视 useState 时,我遇到了同样的问题:
it('increment counter correctlry', () => {
let wrapper = shallow(<Card />);
const setState = jest.fn();
const useStateSpy = jest.spyOn(React, 'useState');
useStateSpy.mockImplementation((init) => [init, setState]);
const button = wrapper.find("button")
button.simulate('click');
expect(setState).toHaveBeenCalledWith(1);
})
此测试失败,运行测试后出现此错误:
Expected: 1
Number of calls: 0
我究竟做错了什么??
解决方案
在enzyme
v3 中,您应该在触发点击处理程序后重新找到h2
浅层包装器。然后您将获得新的h2
浅包装器引用,其中包含counter
. 查看migration-from-2-to-3.html#calling-props-after-a-state-change了解更多信息。
例如
Counter.jsx
:
import React, { useState } from 'react';
export const Counter = () => {
const [counter, setCounter] = useState(0);
const handleClick = () => {
setCounter(counter + 1);
};
return (
<div>
<h2>{counter}</h2>
<button onClick={handleClick} id="button">
increment
</button>
</div>
);
};
Counter.text.jsx
:
import { shallow } from 'enzyme';
import React from 'react';
import { Counter } from './Counter';
describe('64148085', () => {
it('increment counter correctly', () => {
const wrapper = shallow(<Counter />);
const button = wrapper.find('button');
button.simulate('click');
expect(wrapper.find('h2').text()).toBe('1');
});
});
带有覆盖率报告的单元测试结果
PASS src/stackoverflow/64148085/Counter.test.tsx
64148085
✓ increment counter correctly (12ms)
-------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
counter.tsx | 100 | 100 | 100 | 100 | |
-------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.472s, estimated 12s
推荐阅读
- apache-spark - AnalysisException:无法解析给定输入列的“公司”:[spark_catalog.default.companies.value]
- python - 将列值(文本数据)拆分/切片成多行
- javascript - Chrome(和 Edge)要求几个麦克风权限
- java - 重命名顶级文件夹后如何在 intelli j 中重建项目模块?
- css - 使用 css 更改 svg 路径
- node.js - 将 Socket.IO 用于聊天应用程序,但 MongoDB/Mongoose 仅用于用户
- go - 需要运行几个 func() bool 并得到第一个 false
- javascript - 返回前如何格式化数据json?
- css - 带有 translateZ 的 CSS 透视图在 Safari 上不起作用
- python - 如何评估包含熊猫列表的列?