【发布时间】:2021-12-29 07:27:18
【问题描述】:
我需要测试在触发按钮单击后使用 opened={true} 属性调用反应组件。我正在使用testing-library (testing-library/react + testing-library/jest-dom)。
我使用类似的东西模拟了组件
import Component from "./path-to-file/component-name"
...
jest.mock("./path-to-file/component-name", () => {
return jest.fn().mockImplementation(() => {
return null
})
})
我第一次尝试:
expect(Component).toBeCalledWith(expect.objectContaining({"opened": true}))
expect(Component).toHaveBeenCalledWith(expect.objectContaining({"opened": true}))
expect(Component).toHaveBeenLastCalledWith(expect.objectContaining({"opened": true}))
但我得到了Error: expect(jest.fn()).toBeCalledWith(...expected)。
expect.objectContaining({"opened": expect.anything()}) 也是如此
甚至对于expect(Component).toBeCalledWith(expect.anything())
我也试过expect(ChartMenu.mock).toBeCalledWith(expect.anything())。我得到了一个不同的错误但仍然无法正常工作(这次错误是Error: expect(received).toBeCalledWith(...expected) + Matcher error: received value must be a mock or spy function)
谢谢你的建议!
编辑:这是我要测试的组件的简化版本:
const Component = () => {
const [chartMenuOpened, setChartMenuOpened] = useState(false)
return (
<Flex>
<EllipseIcon onClick={() => setChartMenuOpened(true)}>
+
</EllipseIcon>
<ChartMenu
opened={chartMenuOpened}
close={() => setChartMenuOpened(false)}
/>
</Flex>
)
}
基本上,我想确保单击+ 图标时,将打开菜单(或使用打开值调用)。问题是我无法渲染 ChartMenu,因为它需要多个 props 和 redux 状态。
我最终能够模拟 useState 以检查 setState 是否从图标组件中正确调用(以确保组件未来不会发生会破坏此 using this post 的更改) .
但我仍然非常感谢这个问题的答案:是否有任何方法可以在反应组件上创建间谍或类似的东西并检查调用它的道具?主要是因为这是一个相当简单的例子,我只有一个状态。但情况可能并非总是如此。或者关于如何正确测试这种交互是否真的很受欢迎的任何好主意。
【问题讨论】:
-
请提供您要测试的组件代码。
-
嗨!我编辑了这个问题。非常感谢!
标签: reactjs jestjs react-testing-library testing-library