简体   繁体   中英

How to get Jest to find modules imported in components?

When I try to run npm jest, the test suite fails to run and gives this error message:

Cannot find module 'app/utils' from 'MoreModal.js'

          1 | import React from 'react';
          2 | import { Link } from 'react-router';
        > 3 | import { fn, api } from 'app/utils';

My jest config is

"jest": {
        "setupTestFrameworkScriptFile": "<rootDir>/js/__tests__/setup/setupEnzyme.js",
        "testPathIgnorePatterns": ["<rootDir>/js/__tests__/setup/"],
    },

I've tried fiddling with moduleDirectories, but that does nothing.

My enzyme setup is

Enzyme.configure({ adapter: new Adapter() });

The test:

describe('<MoreModal />', () => {
    describe('render()', () => {
        test('renders the component', () => {
            const wrapper = shallow(<MoreModal />);
            const component = wrapper.dive();

            expect(toJson(component)).toMatchSnapShot();
        })
    })
})

How do I get jest to correctly find the modules in the component?

Your bundler probably has something set up for resolution to make app/utils work like that.

If you're using Webpack, https://www.npmjs.com/package/jest-webpack-resolver will help you wire up Jest to use the same resolution rules.

You can try the following:

"jest":{
    "modulePaths": [
        "<rootDir>/app"
    ],
    "moduleDirectories": [
        "app"
    ]
}

According to Jest documentation :

An alternative API to setting the NODE_PATH env variable, modulePaths is an array of absolute paths to additional locations to search when resolving modules. Use the string token to include the path to your project's root directory. Example: ["/app/"].

It is also possible that your bundler resolves your modules relative to a different directory as very well mentioned by @AKX. Is "app/utils" in the root folder of your project or inside a different one? If that's the case your jest configuration should match your bundler's.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM