How to match called with an array with order?
For example, I have tried, but failed as it ignore order:
expect(fn()).toBeCalledWith(expect.arrayContaining([1,2,3]))
My goal is success when calling with [1,2,3] [1,2,3,4] [1,10,2,7,8,9,3] but not [3,2,1]
The above code give me pass when called with [3,2,1], how can I achieve this goal?
This end up can be done with expect.extend, which I can create my custom matcher.
https://jestjs.io/docs/expect#expectextendmatchers
expect.extend({
arrayContainingWithOrder(received, sample) {
let index = 0;
for (let i = 0; i < received.length; i++) {
if (received[i] === sample[index]) {
index++;
}
}
const pass = index === sample.length;
if (pass) {
return {
message: () =>
`expected ${received} not to be contain ${sample} with order`,
pass: true,
};
} else {
return {
message: () =>
`expected ${received} to be contain ${sample} with order`,
pass: false,
};
}
},
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With