开玩笑:expect.arrayContaining 有顺序

jest: expect.arrayContaining with order

如何将 called 与带顺序的数组匹配?

例如,我试过,但由于忽略顺序而失败:

expect(fn()).toBeCalledWith(expect.arrayContaining([1,2,3]))

我的目标是在使用 [1,2,3] [1,2,3,4] [1,10,2,7,8,9,3] 而不是 [3,2,1] 调用时成功 上面的代码在用 [3,2,1] 调用时让我通过,我怎样才能实现这个目标?

您可以将预期的数组和调用的参数转换为 1,2,3 之类的字符串。然后你可以使用 expect.stringContaining 而不是 expect.arrayContaining。例如

const mockedFunction = jest.fn()
expect(mockedFunction).toHaveBeenCalled() //make sure your mocked function get called
const calledArray = mockedFunction.mock.calls[0][0] //get first argument which is your array
const expectedArray = [1,2,3]
const calledArrayString = calledArray.filter(value => expectedArray.includes(value)).join(",") //only keep contained values
const expectedArrayString = expectedArray.join(",")
expect(calledArrayString).toEqual(expect.stringContaining(expectedArrayString))

这可以通过 expect.extend 完成,我可以创建自定义匹配器。 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,
      };
    }
  },
});