简体   繁体   English

Jasmine:测试 toHaveBeenCalledWith(params) 其中 params 是一个对象

[英]Jasmine: Testing toHaveBeenCalledWith(params) where params is an object

I'm doing some testing with Jasmine, having a strange result when looking for expected params as a result of a Spy.我正在用 Jasmine 做一些测试,在寻找预期的参数时有一个奇怪的结果作为间谍的结果。

I'm testing using the toHaveBeenCalledWith() method and looking for something like this:我正在使用 toHaveBeenCalledWith() 方法进行测试并寻找如下内容:

{
  foo: bar,
  thing: [1,2,3],
  etc: function() { blah; }
}

It gives a fail, but the error message seems to confirm the exact same object is actually being found.它给出了失败,但错误消息似乎确认实际上找到了完全相同的对象。

Any reasons why this might be the case?为什么会出现这种情况?

Equivalent function definitions are not equal.等效函数定义不相等。 So,所以,

function() { return 'blah'; } == function() { return 'blah'; } // returns false

You have to reference the same function definition when using toHaveBeenCalledWith() for Jasmine to consider it equal to the argument passed to the spied object's method.在为 Jasmine 使用 toHaveBeenCalledWith() 时,您必须引用相同的函数定义,以将其视为传递给被监视对象的方法的参数。 Are you maybe passing in a new object definition (like the object you included in your question) to toHaveBeenCalledWith()?您是否可能向 toHaveBeenCalledWith() 传入一个新的对象定义(例如您在问题中包含的对象)? That will not pass the Jasmine assertion.那不会通过 Jasmine 断言。

Here is the Jasmine spec I ran which illustrates what I said.这是我运行的 Jasmine 规范,它说明了我所说的。 There is a succeeding example and a failing example:有一个成功的例子和一个失败的例子:

describe("A spy example", function() {
    var baz  = {
        foo: 'bar',
        thing: [1,2,3],
        etc: function() { }
    };

    beforeEach(function() {
        spyOn(baz, 'etc');
        baz.etc(baz);
    });

    it("succeeds", function() {
        expect(baz.etc).toHaveBeenCalledWith(baz);
    });

    it("fails", function() {
        expect(baz.etc).toHaveBeenCalledWith({
            foo: 'bar',
            thing: [1,2,3],
            etc: function() { }
        });
    });
});

A possible solution is to use: Custom asymmetric equality tester.一个可能的解决方案是使用:自定义非对称相等测试器。 Which let's the tester decide how to determine equality.这让测试人员决定如何确定相等性。 Example:例子:

describe("A spy example", function() {

var baz  = {
    foo: 'bar',
    thing: [1,2,3],
    etc: function() { }
};

beforeEach(function() {
    spyOn(baz, 'etc');
    baz.etc(baz);
});

it("succeeds", function() {
    expect(baz.etc).toHaveBeenCalledWith(baz);
});

var customTester = {
  asymmetricMatch: function(actual) {
    return actual.foo === 'bar' && 
           actual.thing.length === 3 // && ... ( any deep comparison method you wish to use)
  }
};

it("succeeds too", function() {
    expect(baz.etc).toHaveBeenCalledWith(customTester);
});

}); });

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM