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

你离开我真会死。 提交于 2020-02-25 06:24:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/57489370/moduledirectories-key-does-not-make-it-possible-to-import-my-test-utils

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!