[英]Javascript tests - How to compare two objects in Jasmine
Javascript TDD的新手,目前與Jasmine合作。
比較兩個對象時出現問題。
我正在測試的函數被分配一個作為定義傳遞的對象(我正在使用require)-
define(
['jquery',
'src/frameManager'],
function($,FrameManager){
return {
// OBJECTS
frameManager : FrameManager,
....
}
這是我的測試:
define(['init', '../../../src/frameManager'], function (init, frameManager) {
...
it("Init to contain property frameManager with type frameManager", function() {
console.log(init.frameManager)
console.log(frameManager)
expect(init.frameManager).toEqual(jasmine.any(frameManager));
});
....
});
兩個控制台日志向我顯示了完全相同的對象,但出現此錯誤:
TypeError: Expecting a function in instanceof check, but got #<Object>
我也嘗試了上面沒有jasmine.any的方法:
expect(init.frameManager).toEqual(frameManager);
但是仍然沒有喜悅。 在這種情況下,我得到以下錯誤:
Error: Expected Object({ iframe: ({ context: HTMLNode, selector: '#preview-frame' }), frameContents: false, parent: false, templateBody: false, parsedTemplate: false, services: Object({ url: false, type: false, data: false, dataType: false, callback: false, call: Function, set: Function, ajaxService: Function, isEmpty: Function }), init: Function, setOptions: Function, parseIframe: Function, registerEvents: Function, getParsedTemplate: Function, populateIframe: Function }) to equal Object({ iframe: ({ context: HTMLNode, selector: '#preview-frame' }), frameContents: false, parent: false, templateBody: false, parsedTemplate: false, services: Object({ url: false, type: false, data: false, dataType: false, callback: false, call: Function, set: Function, ajaxService: Function, isEmpty: Function }), init: Function, setOptions: Function, parseIframe: Function, registerEvents: Function, getParsedTemplate: Function, populateIframe: Function }).
如您所見,兩個對象完全相同...有人有任何建議嗎?
謝謝。
深入比較兩個對象的最簡單方法是使用下一個條件
JSON.stringify(obj1) == JSON.stringify(obj2);
因此,只需修改您的代碼
expect(JSON.stringify(init.frameManager)).toEqual(JSON.stringify(frameManager));
如果您在測試中多次使用對象比較,請考慮創建自定義匹配器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.