Jasmine toEqual 用于复杂对象(与函数混合) [英] Jasmine toEqual for complex objects (mixed with functions)

查看:15
本文介绍了Jasmine toEqual 用于复杂对象(与函数混合)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一个函数,有时会返回一个包含一些函数的对象.当使用 expect(...).toEqual({...}) 时,它似乎与那些复杂的对象不匹配.具有函数或 File 类(来自输入类型文件)的对象,它就是不能.如何克服?

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 complex objects. Objects having functions or the File class (from input type file), it just can't. How to overcome this?

推荐答案

正如 Vlad Magdalin 在评论中指出的那样,将对象制作成 JSON 字符串,它可以尽可能深,并且函数和 File/FileList 类.当然,在函数上不使用 toString(),也可以直接调用 'Function'

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);

这篇关于Jasmine toEqual 用于复杂对象(与函数混合)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆