Nested include assertion on arrays #887

Open
astorije opened this Issue Dec 17, 2016 · 2 comments

Projects

None yet

3 participants

@astorije
Member

Matrices are often represented as arrays of arrays. There is no documentation for this, but it seems like this would be an acceptable statement:

expect([
  [0, "a", 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0],
]).to.deep.include("a");

It fails with the following AssertionError:

AssertionError: expected [ Array(4) ] to include 'a'

Flattening the array being evaluated works (but there is no native .flatten() in JS, one needs to use Lodash/Underscore.js, or test against Immutable.js structures...), I was wondering if there was a better alternative.

I guess depending on the possibility to do so, this issue can be seen as either:

  • A question: Am I missing an obvious assertion here? I know there is recent work for v4 around deep/nested, are there any changes that can make this possible?
  • A feature-request: Would it be reasonable to update .deep.include() to fit the example above?
@lucasfcosta
Member

Hi @astorije thanks for sharing your thoughts.

This feature seems really useful and IMO we could have it, but I'm not a big fan of using the deep to represent it since it could cause confusion to our users, maybe we can come up with a more precise name in order to avoid that.

I'm not sure this will be possible in v4 even after the deep and nested changes. The deep flag will now allow deep comparisons instead of strict comparisons and nested will allow checking nested properties.

I also think we don't necessarily need Lodash/Underscore to flatten an array of arrays, I think it would just be a matter of using .apply on Array.prototype.concat passing an empty array for it to bind to this and the target array to be flattened as the second argument. This will also guarantee there won't be any changes to the target array.

If you want to read more about the deep/nested changes, @meeber did a really good job detailing those changes at #743. All the related PRs are there too.

Let me know if I misunderstood anything you've said or if you disagree with anything.

Thanks 😄

@meeber
Contributor
meeber commented Dec 18, 2016

In Chai v4, one approach would be:

  expect([
    [0, "a", 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ]).to.have.nested.property("[0][1]", "a");

I think having a flag to allow include to traverse a matrix is useful and interesting, but my initial impression is that it's plugin territory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment