user15963491
user15963491

Reputation: 113

jest: expect.arrayContaining with order

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?

Upvotes: 3

Views: 5792

Answers (1)

user15963491
user15963491

Reputation: 113

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,
      };
    }
  },
});

Upvotes: 1

Related Questions