testing - Jasmine spy 示例如何工作

标签 testing jasmine

全部;

我刚开始学习 Jasmine(2.0.3 版),当我进入 Spies 部分时,第一个示例让我感到困惑:

describe("A spy", function() {
  var foo, bar = null;

  beforeEach(function() {
    foo = {
      setBar: function(value) {
        bar = value;
      }
    };

    spyOn(foo, 'setBar');

    foo.setBar(123);
    foo.setBar(456, 'another param');
  });

  it("tracks that the spy was called", function() {
    expect(foo.setBar).toHaveBeenCalled();
  });

  it("tracks all the arguments of its calls", function() {
    expect(foo.setBar).toHaveBeenCalledWith(123);
    expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
  });

  it("stops all execution on a function", function() {
    expect(bar).toBeNull();
  });
});

我想知道是否有人可以解释为什么 setBar 函数不影响 describe block 中定义的栏?Jasmine spy 如何处理这个问题?

谢谢

最佳答案

因为您实际上并没有执行这些方法。

如果你想让这个测试失败:

it("stops all execution on a function", function() {
    expect(bar).toBeNull();
});

在这些调用之后:

foo.setBar(123);
foo.setBar(456, 'another param');

然后你应该为你的 spy 调用and.callThrough

spyOn(foo, 'setBar').and.callThrough();

来自 documentation

Spies: and.callThrough

By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation.

关于您的问题,“jasmine 如何处理这个问题?”

here你可以读到一个基本的解释:

Mocks work by implementing the proxy pattern. When you create a mock object, it creates a proxy object that takes the place of the real object. We can then define what methods are called and their returned values from within our test method. Mocks can then be utilized to retrieve run-time statistics on the spied function such as:

How many times the spied function was called.
What was the value that the function returned to the caller.
How many parameters the function was called with.

如果你想要所有的实现细节,你可以查看 Open Source 的 Jasmine 源代码 :)

在这个源文件 CallTracker 中,您可以看到如何收集有关方法调用的数据。

关于 the proxy pattern 的更多信息。

关于testing - Jasmine spy 示例如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32512876/

相关文章:

testing - 如何测试依赖 Meteor.user() 的 meteor 方法

c++ - 用 C++ 进行宾果测试

sql - 转储所有模式和触发器并将它们导入另一个 Oracle 数据库

ruby-on-rails-3 - Rack::Test 使用 JSON 的 PUT 方法无法将 JSON 转换为参数

Angular6 Jasmine TypeError : expect(. ..).toBeVisible 不是一个函数

javascript typeerror 它不是构造函数

node.js - Mocha 测试 done() 和 done 作为函数参数之间的区别

android - Firebase 测试实验室,Robo 测试创建问题。

javascript - 我如何模拟没有索引的键值对列表( Angular )?

jasmine - karma Jasmine 错误: Unexpected request: GET but i'm doing a POST