Skip to content
Advertisement

Why jest is not working with imported test data?

Here a test data defined in sum-test-cases.js with the following

const sumTestCases = [
  {a: 1, b: 1, expected: 2},
  {a: 1, b: 2, expected: 3},
  {a: 2, b: 1, expected: 3},
];

exports.sumTestCases = sumTestCases;

Here is the jest test file sum.test.js with the following

const sumTestCases = require('./sum-test-cases');
test.each(sumTestCases)('.add($a, $b)', ({a, b, expected}) => {
  expect(a + b).toBe(expected);
});

The test failed with the following error:

 ● .add($a, $b)

`.each` must be called with an Array or Tagged Template Literal.

Instead was called with: {"sumTestCases": [Array]}

  1 | const sumTestCases = require('./sum-test-cases');
> 2 | test.each(sumTestCases)('.add($a, $b)', ({a, b, expected}) => {
    | ^
  3 |   expect(a + b).toBe(expected);
  4 | });
  5 |

However, instead of importing the data from another file, if I define the data within the test file like the following, the test works as expected.

const sumTestCases = [
  {a: 1, b: 1, expected: 2},
  {a: 1, b: 2, expected: 3},
  {a: 2, b: 1, expected: 3},
];

test.each(sumTestCases)('.add($a, $b)', ({a, b, expected}) => {
  expect(a + b).toBe(expected);
});

The test data is exactly the same, why it’s only working if the data is defined within the test file, and fails when the test data is defined in another file and imported into the test file?

Advertisement

Answer

The module.exports that exists in one file is the exact same thing that a require returns in a different file. This:

// file 1
exports.sumTestCases = sumTestCases;

// file 2
const theImport = require('./sum-test-cases');

is nearly the same as doing, in a single file:

const objectToExport = {
  sumTestCases: sumTestCases
};

const theImport = objectToExport;

Like the error says:

Instead was called with: {"sumTestCases": [Array]}

You’re passing an object, not an array.

Either assign the whole array as the export:

module.exports = sumTestCases;

or access the sumTestCases property of the object after importing.

const { sumTestCases } = require('./sum-test-cases');
Advertisement