2015-03-13 39 views
0

對於JavaScript TDD非常新穎,並且現在與Jasmine一起工作。JavaScript測試 - 如何比較茉莉花中的兩個對象

我有一個比較兩個對象的問題。

爲一個定義(我使用的需要)通過我測試的功能被分配一個對象 -

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 }). 

正如你可以看到,這兩個對象是完全一樣的... 有沒有人有什麼建議?

謝謝。

+0

你濫用jasmine.any()函數。從代碼中刪除它,它應該工作 – miszczu 2015-03-13 11:35:21

+0

謝謝,我已經嘗試過,但它沒有工作。我會更新細節。 – Ste77 2015-03-13 11:48:21

回答

0
深入比較兩個對象

最簡單的方法是使用一個條件

JSON.stringify(obj1) == JSON.stringify(obj2); 

所以只要修改代碼

expect(JSON.stringify(init.frameManager)).toEqual(JSON.stringify(frameManager)); 

如果您在測試中使用對象比較多次,考慮創建custom matcher