javascript Karma/Jasmine 规范 -- 预期 { } 等于 { }

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26350153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:51:22  来源:igfitidea点击:

Karma/Jasmine spec -- Expected { } to equal { }

javascriptangularjsphantomjskarma-runnerkarma-jasmine

提问by Sasha

I'm running a Karma spec to test the functionality of an Angular BaseClass for my models that is outlined in an Egghead.io tutorial.

我正在运行 Karma 规范来测试 Egghead.io 教程中概述的模型的 Angular BaseClass 的功能。

The behavior seems to be working, but I'm running into a weird error:

该行为似乎有效,但我遇到了一个奇怪的错误:

PhantomJS 1.9.7 (Mac OS X) BCCache adds a cache to the model FAILED
  Expected {  } to equal {  }.
  Error: Expected {  } to equal {  }.

What I could find of this error(it's hard to search, given the characters -- suggests that toEqualshould be able to recognize the two objects' equivalence -- so I'm a little stumped.

我能从这个错误中找到什么(鉴于字符很难搜索 - 表明toEqual应该能够识别两个对象的等效性 - 所以我有点难住。

Here's the spec code (coffeescript) :

这是规范代码(咖啡脚本):

describe 'BCCache', ->
  it "adds a cache to the model", ->
    expect(Post.cached).toEqual({})

And here's what it's testing:

这是它正在测试的内容:

base.coffee

基础咖啡

angular.module("BaseClass")
  .factory "BCBase", ['BCCache', (Cache) ->
    Base = (attributes) ->
      _constructor = this
      _prototype = _constructor.prototype

      _constructor.cached = new Cache()

    return Base
  ]

cache.coffee

缓存咖啡

angular.module('BaseClass')
  .factory 'BCCache', -> 
    Cache = ->    
    return Cache

The spec is basically asserting that the cachedmethod (currently) returns a new empty object, which the cache.coffeefile seems to successfully do. But somehow, Karma doesn't see the two empty objects as equivalent. Any idea why? I'm a little stumped.

该规范基本上断言该cached方法(当前)返回一个新的空对象,该cache.coffee文件似乎成功地做到了。但不知何故,Karma 并不认为这两个空对象是等价的。知道为什么吗?我有点难住了。

回答by SomeKittens

Post.cachedis an instance of Cache, while your {}is just a boring ol' Object. Jasmine considers having a different constructor a valid reason to fail a toEqualscomparison.

Post.cached是 的一个实例Cache,而 your{}只是一个无聊的 ol' Object。Jasmine 认为使用不同的构造函数是toEquals比较失败的正当理由。

If you want to check equality as above, you can do something like:

如果您想检查上述相等性,您可以执行以下操作:

var mockCache = new Cache();
expect(Post.cached).toEqual(mockCache);

Alternatively, you could just check if it's an empty object:

或者,您可以检查它是否为空对象:

expect(Object.keys(Post.cached).length).toBe(0);

Thanks to Jeff Storey for the link to the code: https://github.com/pivotal/jasmine/blob/master/src/core/matchers/matchersUtil.js#L143

感谢 Jeff Storey 提供代码链接:https: //github.com/pivotal/jasmine/blob/master/src/core/matchers/matchersUtil.js#L143