Home > database >  Jest cuts off received array
Jest cuts off received array

Time:07-10

I use Jest to test if a large array contains a given value:

it('should contain x', () => {
  const myArray: string[] = myFunction();

  expect(myArray).toContain('x');
});

When the test fails, Jest cuts off the received array:

Expected value: "x"
Received array: ["a", "b", "c", "d", "e", "f", "g", "h", ...]

This makes it difficult for me to check why the test failed. Can I force Jest force to print the entire received array instead of cutting it off?

CodePudding user response:

You could check this answer.

In your specific use case, I would:

describe("log long array", () => {
  it("logs long array", () => {
    const testArray: number[] = Array.from(Array(10000).keys()),
      expectedNumber = 99999999;

    try {
      expect(testArray).toContain(expectedNumber);
    } catch {
      console.log("Test failed! Array:", JSON.stringify(testArray));
      expect(testArray).toContain(expectedNumber);
    }
  });
});

You could also catch and log the error if you want

Note that I'm calling the same expect twice, as I still want to have the normal Jest behavior for my failing test

Alternatively, you could look into extending jest, allowing expect to have custom error messages with, for example, this package, or creating a custom matcher (docs here)

  • Related