Jasmine toEqual for complex objects (mixed with functions)

后端 未结 5 1839
鱼传尺愫
鱼传尺愫 2020-12-16 13:00

Currently, I have a function that sometimes return an object with some functions inside. When using expect(...).toEqual({...}) it doesn\'t seem to match those c

5条回答
  •  眼角桃花
    2020-12-16 13:14

    If anyone is using node.js like myself, the following method is what I use in my Jasmine tests when I am only concerned with comparing the simple properties while ignoring all functions. This method requires json-stable-stringify which is used to sort the object properties prior to serializing.

    Usage:

      var stringify = require('json-stable-stringify');
    
      var obj1 = {
        func: function() {
        },
        str1: 'str1 value',
        str2: 'str2 value',
        nest1: {
        nest2: {
            val1:'value 1',
            val2:'value 2',
            someOtherFunc: function() {
            }
          }
        }
      };
    
      var obj2 = {
        str2: 'str2 value',
        str1: 'str1 value',
        func: function() {
        },
        nest1: {
          nest2: {
            otherFunc: function() {
            },
            val2:'value 2',
            val1:'value 1'
          }
        }
      };
    
      it('should compare object properties', function () {
        expect(stringify(obj1)).toEqual(stringify(obj2));
      });
    

提交回复
热议问题