javascript - 在 VueJS 中模拟一个简单的函数,JEST
问题描述
我正在努力模拟列表组件中的删除功能。
我的测试现在看起来像这样
describe("delete a todo", () => {
test("should have todo removed", async () => {
const deleteItem = jest.fn();
const items = [{ id: 1, name: "ana", isComplete: false }];
const wrapper = shallowMount(Todo, items);
console.log(wrapper);
const deleteButton = ".delete";
wrapper.find(deleteButton).trigger("click");
expect(deleteItem).toHaveBeenCalledWith("1");
});
目前,当我运行测试时,错误读取。 测试错误
该应用程序工作正常,但我没有在我的测试中正确模拟删除功能,因为“新笔记”仍在通过。我究竟做错了什么?
以防万一,这是我正在测试的文件的一部分。
methods: {
addItem() {
if (this.newItem.trim() != "") {
this.items.unshift({
// id: createUID(10),
id: uuid.v4(),
completed: false,
name: this.newItem
});
this.newItem = "";
localStorage.setItem("list", JSON.stringify(this.items));
this.itemsLeft = this.itemsFiltered.length;
}
},
removeItem(item) {
const itemIndex = this.items.indexOf(item);
this.items.splice(itemIndex, 1);
localStorage.setItem("list", JSON.stringify(this.items));
this.itemsLeft = this.itemsFiltered.length;
},
此外,对于更多代码,您可以从以下链接获取: https ://github.com/oliseulean/ToDoApp-VueJS
解决方案
我认为您必须对原始测试用例进行一些更改
- 将 jest.fn() 更改为 jest.spyOn(Todo.methods, 'deleteItem') 因为您必须跟踪对 Todo 组件中方法对象的调用。参考:https ://jestjs.io/docs/jest-object
- 等待点击事件被 await 触发
- 使用 toHaveBeenCalledTimes 不使用 toHaveBeenCalledWith("1")
所以你的最终测试用例看起来像这样
describe("delete a todo", () => {
test("should have todo removed", async () => {
const removeItem = jest.spyOn(Todo.methods, 'removeItem')
const items = [{ id: 1, name: "ana", isComplete: false }];
const wrapper = shallowMount(Todo, items)
await wrapper.find('.delete').trigger('click')
expect(removeItem).toHaveBeenCalledTimes(1);
});
});
推荐阅读
- amazon-web-services - 将自定义域添加到 lambda 的最佳方法?
- odoo - 如何在odoo树视图onclick按钮中创建记录?
- php - 如何在服务器上使用 SSH 命令执行本地 Shell 脚本?
- angular - 角度示意图:未找到:我的示意图错误
- c# - c#中new object()到底做了什么
- python - 如何在Python中提取第一个字符
- javascript - 用 Javascript 编写代码,使用 if、else 和 prompt。
- java - 找不到参数的方法 abiFilters() [x86]
- c++ - 使用模板前向声明所有未来函数会导致歧义,而不是将声明与定义配对
- mysql - 使用 javafx 将图像上传到数据库