【问题标题】:Javascript tests - How to compare two objects in JasmineJavascript 测试 - 如何比较 Jasmine 中的两个对象
【发布时间】:2015-03-13 11:11:09
【问题描述】:

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

如您所见,两个对象完全相同... 有人有什么建议吗?

谢谢。

【问题讨论】:

  • 你误用了 jasmine.any() 函数。从您的代码中删除它,它应该可以工作
  • 谢谢,我试过了,但是没有用。我会更新更多细节。

标签: javascript unit-testing tdd jasmine


【解决方案1】:

深入比较两个对象的最简单方法是使用下一个条件

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

所以只要修改你的代码

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

如果您在测试中多次使用对象比较,请考虑创建custom matcher

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    相关资源
    最近更新 更多