Chai assertion testing whether object structure contains at least other object structure

孤街浪徒 提交于 2019-12-01 05:18:47

There are a couple of plugins for Chai which can solve this issue.

chai-subset

There is this subset plugin for Chai, that should be able to do this.

I'm using Mocha in the browser, but although it should be browser compatible, I haven't got this plugin working yet.

Anyway, this library contains the generic answer to the question, and after including it, the following line should work:

sut.should.containSubset(expected);

chai-shallow-deep-equal

chai-subset seemed to lack the version that is required to run it in the browser, so I went on looking for plugins. Another one that I found is chai-shallow-deep-equal.

This plugin can be used fine in the browser too. Had it up and running in seconds after downloading it from Git and using the description on the plugin page, resulting in:

sut.should.shallowDeepEqual(expected);

It will now nicely ignore extra properties in sut, but it will also give nice assertions when properties as missing or different in expected. You'll get a message like this:

AssertionError: Expected to have "2" but got "20" at path "/foo/qux".

It doesn't show all assertions, though. If you have two errors in the object, you'll only get one (the first) assertion error. To me that's not really an issue, but it could be confusing, because it might look like a fix you made introduced a new issue while it was already there.

chai-fuzzy

I've not tried chai-fuzzy, (GitHub) myself yet, but it seems it can solve the same problem too and its repository also contains the browser compatible version of the plug-in. However, it also requires yet another library, Underscore, which seems a bit overkill for the purpose. It's syntax would look like this:

sut.should.be.like(expected);

Correct me if I understood wrong but the following will work with plain chai.

expect({foo: {bar: 10}}).to.have.deep.property('foo.bar', 10); // Success
expect({foo: {bar: 11}}).to.have.deep.property('foo.bar', 10); // Fail
expect({foo: {qux: 20}}).to.have.deep.property('foo.bar', 10); // Fail
expect({baz: 'a', foo: {bar: 10, baz: 20}}).to.have.deep.property('foo.bar', 10); // Success
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!