Jasmine JavaScript Testing - toBe vs toEqual

后端 未结 7 1753
不思量自难忘°
不思量自难忘° 2020-11-28 17:32

Let\'s say I have the following:

var myNumber = 5;
expect(myNumber).toBe(5);
expect(myNumber).toEqual(5);

Both of the above tests will pass

7条回答
  •  一生所求
    2020-11-28 18:25

    Looking at the Jasmine source code sheds more light on the issue.

    toBe is very simple and just uses the identity/strict equality operator, ===:

      function(actual, expected) {
        return {
          pass: actual === expected
        };
      }
    

    toEqual, on the other hand, is nearly 150 lines long and has special handling for built in objects like String, Number, Boolean, Date, Error, Element and RegExp. For other objects it recursively compares properties.

    This is very different from the behavior of the equality operator, ==. For example:

    var simpleObject = {foo: 'bar'};
    expect(simpleObject).toEqual({foo: 'bar'}); //true
    simpleObject == {foo: 'bar'}; //false
    
    var castableObject = {toString: function(){return 'bar'}};
    expect(castableObject).toEqual('bar'); //false
    castableObject == 'bar'; //true
    

提交回复
热议问题