Jasmine toEqual复杂对象(与函数混合) [英] Jasmine toEqual for complex objects (mixed with functions)
问题描述
目前,我有一个函数,有时会返回一个内部有一些函数的对象。当使用 expect(...)。toEqual({...})
时,它似乎与这些复杂对象不匹配。具有函数的对象或文件
类(来自输入类型文件),它不能。如何解决这个问题?
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()
,它可以被称为'函数'
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屋!