【发布时间】:2020-12-04 17:00:01
【问题描述】:
当我尝试直接测试它时,我无法断言函数selectXHandler。因为它是在私有范围内定义的。我无法模拟或监视此功能,因为您无法访问它
export const CheckboxWrapper = ({
x,
y,
z,
a = [],
}: CheckboxWrapperProps) => {
const State = useContext(Context);
const [state, dispatch] = State;
const { Items } = state;
const selectXHandler = () => {
const payload = {
x,
a,
};
dispatch({ type: action, payload });
};
if (y) {
return (
<div className="mt5">
<Checkbox
checked={selectedItems[x] !== undefined}
label={z}
onChange={selectXHandler}
/>
</div>
);
}
return null;
};
const selectXHandler = jest.fn();
await fireEvent.click(checkbox);
expect(checkbox).toBeChecked();
expect(selectXHandler).toHaveBeenCalledTimes(1);
我收到以下错误:
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
【问题讨论】:
-
您应该测试面向公众的行为,而不是内部实现细节。例如。测试你的 UI 元素如何变化,而不是调用什么内部函数
-
我正在研究集成测试,检查功能是否被触发是其中的一部分。 @bsapaka
-
您可以改为模拟 redux 并检查它的调度是否已被调用以及使用什么参数。它也是你的组件“公共接口”,不像里面的一些私人功能。假设,您重命名了您的内部函数 - 应用程序可能因此而损坏吗?不。另一方面,如果您的组件开始调度操作“A”而不是“B”,它可能会破坏您的应用程序。所以用测试覆盖它是有意义的。
-
@contextq 无论是哪种测试,它都应该始终测试公共合约,而不是内部实现。您应该能够以满足正确行为的方式更改任何内部结构,并且测试应该仍然通过。
-
@skyboyer 我没有使用 redux,而是使用 usereducer 和 context 来创建类似的东西。你能用伪代码提出建议吗?
标签: reactjs typescript jestjs react-testing-library