Jasmine toEqual for complex objects (mixed with functions)

后端 未结 5 1833
鱼传尺愫
鱼传尺愫 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:21

    As Vlad Magdalin pointed out in the comments, making the object to a JSON string, it can be as deep as it is, and functions and File/FileList class. Of course, instead of toString() on the function, it could just be called 'Function'

    function replacer(k, v) {
        if (typeof v === 'function') {
            v = v.toString();
        } else if (window['File'] && v instanceof File) {
            v = '[File]';
        } else if (window['FileList'] && v instanceof FileList) {
            v = '[FileList]';
        }
        return v;
    }
    
    beforeEach(function(){
        this.addMatchers({
            toBeJsonEqual: function(expected){
                var one = JSON.stringify(this.actual, replacer).replace(/(\\t|\\n)/g,''),
                    two = JSON.stringify(expected, replacer).replace(/(\\t|\\n)/g,'');
    
                    return one === two;
                }
        });
    });
    
    expect(obj).toBeJsonEqual(obj2);
    

提交回复
热议问题