-
-
Notifications
You must be signed in to change notification settings - Fork 697
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
test array to include an object with a certain key: value #1024
Comments
I think the chai-things plugin does this, but unfortunately it doesn't currently support v4 (and might not even support v3.5). Is the exact array index that contains the the desired property value not known ahead of time? I'd like to learn more about the use case that leads to this kind of test being written, as opposed to something like On an unrelated note, I'd be careful about having a variable like |
Hi meeber,
The array is events array. We represent each event as an object, and one of the properties this object has is 'nameType'. |
Makes sense. In a case like this one, I can understand accepting decreased precision in exchange for increased maintainability. A couple of weeks ago I was thinking about the level of effort of making the |
I have the same issue - thanks for the workaround idea @Segev95 |
Hey @Segev95 thanks for the issue. We've added this to our Roadmap https://github.com/chaijs/chai/projects/2! We'll be releasing chai 5 soon, but for now I'll close this issue because it is tracked on our roadmap. |
@keithamus Is there a solution available through |
This isn't quite what OP was asking for, but in the spirit of contributing workarounds, here's what I came up with: expect(arr.map((e) => e.id).sort()).to.deep.equal([1, 3, 6, 7]); This requires you to test the validity of the entire array, but that happened to work for my use case. This could also be factored out into a helper function: expect(extractProperty(arr, id)).to.deep.equal([1, 3, 6, 7]);
function extractProperty(arr, property) {
return arr.map((e) => e.property).sort();
} To be more in line with what OP is asking, I suppose you could also do something like: expect(arr.map((e) => e['id']).includes( /* ID you're testing for */ )).to.be.true; Which could be rewritten as: expect(propertyValueInArray(arr, 'id', /* ID you're testing for */)).to.be.true;
function propertyValueInArray(arr, property, value) {
return arr.map((e) => e[property]).includes(value);
} |
Hello,
As the title says we found our selves in a situation where we need to check if an array contains an element that one of his properties equals to something.
We tried and search for a couple of hours until we desided to raise an issue about it.
We were able to solve the problem like this:
but we were hoping for something a bit like:
if we missed anything please let us know and if we didnt please consider adding this functionality ;)
The text was updated successfully, but these errors were encountered: