moduleDirectories key does not make it possible to import my test utils

I want to test my Expo React Native app with Jest and @testing-lib/react-native.

I have the following set up in my package.json.

"jest": {
    "preset": "jest-expo",
    "moduleDirectories": [
      "node_modules",
      "test-utils"
    ]
  },

And my folder structure looks like this:

???node_modules/
???test-utils/
???src/
???package.json

src/ contains the test files. I'm testing my configuration with this simple test at src/index.test.js:

import { assert } from 'test-utils';

const sum = (a, b) => a + b;

describe('sum', () => {
  assert({
    given: 'two numbers',
    should: 'add the numbers',
    actual: sum(1, 3),
    expected: 4,
  });
});

Where assert is in test-utils/index.js:

const assert = ({
  given = undefined,
  should = '',
  actual = undefined,
  expected = undefined,
} = {}) => {
  it(`given ${given}: should ${should}`, () => {
    expect(actual).toEqual(expected);
  });
};

export { assert };

If I run my tests I get the error:

Cannot find module 'test-utils' from 'index.test.js'

Why is that? I mean I have configured the moduleDirectories key? ???? How can you fix this? I'd really love to be able to import assert as an absolute path instead of a relative path.

Answers:

Answer

I found the solution. The docs are just bad at the moment.

If you have this folder structure

???node_modules/
???src/
???utils/
???package.json

Then you want to name your module directories like this:

"jest": {
  "preset": "jest-expo",
  "setupFilesAfterEnv": [
    "@testing-library/react-native/cleanup-after-each"
  ],
  "moduleDirectories": [
    "node_modules",
    "utils"
  ]
},

Then within utils/ you want to have the .js file test-utils.js. Then you can import from test-utils in your tests.

So, the key take away is that the name of the module from which you export has to be the name of the .js file. And the folder that you put into moduleDirectories has to contain this .js file.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.