Jest: See if Value is in Array

Created on 4 Nov 2016  路  4Comments  路  Source: facebook/jest

Hey, have a feature request for something I don't think is currently supported. I'm willing to try to implement it, but was hoping to get some feedback before I started coding!

I'm looking for a function that looks like expect(val).toBeContainedIn([arr]). Right now we have expect([arr]).toContain(val) but not the inverse. This new function would be helpful when testing a method that chooses a random word from a string and outputs it, for example.

Like I said, I'm willing to try my hand at implementing this but wanted to know if this is currently supported behavior in an area I've missed? If not, is it something I could add? And finally, can you think of a better name than toBeContainedIn? Seemed a bit wordy to me 馃槗

Most helpful comment

Sorry, maybe I didn't explain it clearly - what I'm looking for is the ability to test if a return value is in an accepted list of values. So for instance, if you have a function named rollDice() you could see if the return value is contained in the array [1, 2, 3, 4, 5, 6]. In practice, it might look like

expect(rollDice()).toBeIn([1, 2, 3, 4, 5, 6])

While there are other ways of testing this particular example, imagine if you were to test something that returned strings instead.

All 4 comments

There is toMatch for strings and regexes. Otherwise I recommend using Array.isArray. Feel free to add a matcher for toBeArray().

Sorry, maybe I didn't explain it clearly - what I'm looking for is the ability to test if a return value is in an accepted list of values. So for instance, if you have a function named rollDice() you could see if the return value is contained in the array [1, 2, 3, 4, 5, 6]. In practice, it might look like

expect(rollDice()).toBeIn([1, 2, 3, 4, 5, 6])

While there are other ways of testing this particular example, imagine if you were to test something that returned strings instead.

expect([1, 2, 3, 4, 5, 6]).toContain(rollDice())

will work just fine then, right? I don't think we need to add a matcher for this. In the next release, expect.extend will be available and you can add your own custom matchers :)

It will, but the documentation lead me to believe that order was an anti-pattern - apologies if I misunderstood! expect.extend sounds perfect, looking forward to it!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

paularmstrong picture paularmstrong  路  66Comments

RyanCCollins picture RyanCCollins  路  93Comments

timoxley picture timoxley  路  76Comments

pfftdammitchris picture pfftdammitchris  路  76Comments

kirlat picture kirlat  路  81Comments