【问题标题】:Jest spyOn is reporting a method was called with a different object than what it was actually called withJest spyOn 报告一个方法被调用的对象与实际调用的对象不同
【发布时间】:2019-01-15 15:24:21
【问题描述】:

我正在使用 Jest spyOn 来跟踪 Vue 路由器上的方法。我正在测试的 Vue 方法如下所示:

myMethod() {
  this.$router.push({ name: "login" });
}

我想确保调用了$router.push,所以在我的测试中我有这个:

const spy = jest.spyOn(wrapper.vm.$router, 'push');
expect(spy).toHaveBeenCalledWith({ name: "login" });

但此测试失败,并出现以下错误:

Expected mock function to have been called with:
        {"name": "login"}
      as argument 1, but it was called with
        {"name": "login", "params": {}, "path": "/login"}.

没问题,我可以将测试更新为以下内容并且可以正常工作:

expect(spy).toHaveBeenCalledWith({
  name: "login",
  params: {},
  path: "/login"
});

我的问题是:为什么 Jest 间谍报告它是用具有三个属性的对象调用的,但是当我们查看实际的方法调用时,它只有一个属性?

【问题讨论】:

  • toHaveBeenCalledTimes(1) 带给你什么?
  • @Krimson 它通过了!
  • 所以我假设它在内部被多次调用?
  • @Krimson 我正在测试的方法只调用 router.push 一次,AFAIK 不应该调用该方法。
  • 哦,我明白你的意思了。我误解了你的回复

标签: vue.js jestjs


【解决方案1】:

vue-routerparamspath 属性添加一些默认值。当您使用spyOn 时,您将检测到由vue-router 分配的其他参数。如果您将spy 显式添加到push 方法,那么您将只看到name 属性。

试试这个:

const spy = jest.fn();
wrapper.vm.$router.push = spy;
expect(spy).toHaveBeenCalledWith({ name: "login" });

【讨论】:

  • 问题是 $router.push 是一个只读属性:/ 这就是我使用间谍而不是用模拟函数覆盖它的原因。我感兴趣的是 spyOn 不会检测到默认添加的任何值。对吗?
猜你喜欢
  • 2020-03-08
  • 1970-01-01
  • 1970-01-01
  • 2019-01-03
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多