javascript - 你如何在 Jasmine/Jest 中对独特的方法调用进行单元测试?
问题描述
我的应用程序中有代码,其中某个函数被调用了 n 次(让我们调用这个函数foo
)。运行时期望是每次调用foo
都是唯一的(使用一组唯一的参数调用)。foo
由于多次使用相同的参数集调用,我的应用程序中有一个最近的错误清单。
我想编写一个测试用例,我可以在其中断言foo
使用一组特定的参数唯一地调用过一次,但我不知道如何在 Jasmine/Jest 中这样做。
我知道 Jasmine 有toHaveBeenCalledOnceWith
匹配器,但它断言它foo
被称为“恰好一次,并且完全带有特定的参数”,这不是我在这种情况下要寻找的。
解决方案
您可以组合toHaveBeenCalledWith()
并toHaveBeenCalledTimes()
获得您想要的行为,您只需要拥有与toHaveBeenCalledWith()
您期望的呼叫数量一样多的 s :
例如:
describe("test", () => {
it("should call not more than unique", () => {
spyOn(callsFoo, 'foo');
callsFoo.somethingThatCallsFoo();
expect(callsFoo.foo).toHaveBeenCalledTimes(2);
expect(callsFoo.foo).toHaveBeenCalledWith({...someArgs});
expect(callsFoo.foo).toHaveBeenCalledWith({...otherUnique});
});
})
如果重复调用不是唯一的,这将失败。
推荐阅读
- python - Python Selenium:有时无法在 iframe 中获取内容
- cytoscape - 如何实现新的节点形状
- google-play - Expo 托管项目密钥库文件和 Google Play 上传密钥库之间的区别
- c++11 - 使用 pybind11 动态加载 libpython
- java - 使用打包的 JRE 编译为 linux 可执行文件
- ajax - 当您期望空结果时,如何防止从 java 服务器端返回 400 代码?
- javascript - 在 javascript 中构建表格并在 1 个单元格中进行粗体测试
- dart - 我想创建每个字母大写的随机英文单词,但我失败了,尽管我遵循与指令显示完全相同的代码
- c++ - 如何在 QCustomPlot 中隐藏绘图区域?
- python - 从多个文件夹中递归查找和复制文件