我正在努力理解如何正确地触发可验证的状态更新。基本上,我有两个案例,我正在尝试测试,这两个案例只与按钮的视觉状态有关。
1)测试按钮是否在视觉上变为选中状态2)测试按钮是否在视觉上变为禁用状态
应用程序
export default function App() {
const [selected, setSelected] = useState(false);
return (
<div className="App">
<h1>Testing Style Update</h1>
<Button
className={`buttonBase ${selected && "buttonSelected"}`}
clicked={() => setSelected(!selected)}
selected={selected}
/>
</div>
);
}
按钮
const Button = ({ className, selected, clicked }) => (
<button className={className} onClick={clicked}>
{selected
? "Click me to Remove the new style"
: "Click me to add a new style"}
</button>
);
export default Button;
测试
import React from "react";
import App from "./App";
import Enzyme, { mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import Button from "./Button";
Enzyme.configure({ adapter: new Adapter() });
describe("App", () => {
it("renders", () => {
mount(<App />);
});
it("button visually becomes selected when clicked", () => {
const wrapper = mount(<App />);
const btn = wrapper.find(Button);
expect(btn).toBeDefined(); // <- passes
expect(btn.hasClass("buttonSelected")).toEqual(false); // <- passes
btn.simulate("click");
wrapper.update();
expect(btn.hasClass("buttonSelected")).toEqual(true);// <- fails
});
从视觉上看,这是预期的。
关于在测试中看到状态正确更新,我遗漏了什么?
我的猜测是,一旦我弄清楚了这一点,我就能够将同样的逻辑应用于禁用的事情。
提前感谢
这里是沙箱:https://codesandbox.io/s/testingreactusestate-3bvv7
更新:基于提供的第一个答案,我能够在我的沙箱中通过测试,但不能在我的开发环境中通过。
Material-UI可能导致了一些差异,但我知道我正在寻找的类名:
以下是dev测试
it("Updates it's classes when selected", () => {
wrapper = mount(
<ul>// required because the FilterListItem is an 'li' element
<FilterListItem/>
</ul>
);
let btn = wrapper.find(Button);
expect(btn).toBeDefined(); // <- PASS
// verify that the correct style is not present
expect(btn.hasClass("makeStyles-selected-5")).toEqual(false);// <- PASS
btn.simulate("click");
// re-find the node
btn = wrapper.find(Button);
expect(btn).toBeDefined(); // <- PASS
// check that the correct style has now been added
expect(btn.hasClass("makeStyles-selected-5")).toEqual(true);//<-FAIL
});
发布于 2020-04-17 02:52:54
你的测试是有意义的,你唯一遗漏的是,对于酶3,你需要在触发事件后重新找到你的组件,因为它的属性不会被更新(reference)。
作为进一步的检查,只需在模拟单击事件之前记录包装器:
btn.simulate("click");
console.log(wrapper.find(Button).debug()); // re-find Button
console.log(btn.debug()); // your code using btn
输出将是
<Button className="buttonBase buttonSelected"...
<Button className="buttonBase false"...
因此,正如您所看到的,组件在click
之后已正确更新。问题就是重新找到你需要测试的组件。
额外好处:你不需要使用update()
https://stackoverflow.com/questions/61253931
复制相似问题