6

Some how chai its not working

promise = doSomething()

expect(promise).to.eventually.equal(obj)

expect(promise).to.eventually.deep.equal(obj)

but in the assertion error I get this

AssertionError: expected {a: "2", b: "3"} to equal {a: "2", b: "3"}

BTW I already try with should and I get the same result

Jacob
  • 77,566
  • 24
  • 149
  • 228
Charlires
  • 863
  • 1
  • 11
  • 30
  • It's working for me with a simple `return expect(Promise.resolve({ a: "2", b: "3" })).to.eventually.deep.equal({ a: "2", b: "3" });`. Are you sure the result truly matches the expected output? – Jacob Jan 19 '16 at 00:50
  • Are you sure you're not running both assertions? Using the `deep` flag is correct, since you shouldn't expect object equality. – Jacob Jan 19 '16 at 00:54
  • No, Im not running both at the same time. @Jacob yes your solution works for me too using `when` but no thru my promise, the weird part is that the assertion error is getting the same values. – Charlires Jan 19 '16 at 01:14
  • What plugins are you using? `chai-as-promised` is what I use. – Jacob Jan 19 '16 at 01:26
  • 1
    I guess maybe the value return from promise is string of `JSON`, like `"{a: '2', b: '3'}"`, if so, try `JSON.parse()` this value before deep equal... – zangw Jan 19 '16 at 01:29
  • @Jacob yes Im using `chai-as-promised` – Charlires Jan 19 '16 at 01:36
  • @zangw Didn't work I try converting both to strings aswell but is not working – Charlires Jan 19 '16 at 01:41
  • @Charlires, any errors for your new test... – zangw Jan 19 '16 at 01:44
  • looking through their issue history, chai might be silently asserting against the string's prototype and other fields you don't normally see or consider on the string object. – worc Aug 27 '18 at 18:33

3 Answers3

4

I guess maybe the value return from promise is string of JSON, like

"{a: '2', b: '3'}"

Which case I met before. If so, try JSON.parse() this value before deep equal operation.

zangw
  • 43,869
  • 19
  • 177
  • 214
1

Seems like chai checks more than the object structure.

I did this inside the promise JSON.parse(JSON.stringify(response)) and that make it work, so according to this question How to copy JavaScript object to new variable NOT by reference? I assume that chai is checking the reference of the objects, which makes no sense to me at all.

Not the solution I was expecting but works for me, is some one has a better solution please share.

Community
  • 1
  • 1
Charlires
  • 863
  • 1
  • 11
  • 30
0

Object.getOwnPropertyNames(obj) is a good way to look at what the object actually contains, in the case that they are both objects, look the same even in a console log but are not the same.

For example, chai deep.equal will recognize {a:1, b:2} and the similar object from a Mongoose instance as not the same but it wont actually tell you what is different ("+ expected - actual" being empty). Object.getOwnPropertNames will show the real contents of the object.

jaywink
  • 280
  • 3
  • 14