Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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,
      };
    }
  },
});
about 4 years ago · Juan Pablo Isaza Relatório

0

You can convert your expected array and called argument to strings like 1,2,3. And then you can use expect.stringContaining instead of expect.arrayContaining. For example

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))
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda