简体   繁体   中英

Automatically replace imports in jest

I am trying to set up a testbench for a more complex app. We have the issue that our app wants to call backend code which needs to be mocked in order to keep the testbench fast. Therefor we have two files per module:

connector.ts and connector.mocked.ts the first contains the "live" code, the second one contains some mocked/ dummy implementation. In our Modules we then import them by just doing

import {...} from './connector.ts'

which will be executed directly in our app, or in storybook will be rewritten to the connector.mocked.ts . In Storybook this happens in the global config:

module.exports = {
  ...
  webpackFinal: (config) => {
    ...
    config.resolve.alias = {
      ...config.resolve.alias,
      './connector': './connector.mocked',
      '@': path.resolve(__dirname, '..'),
    }
  }
}

whats the equivalent in Jest for this? I don't want to write this for every test as the unit under test might not use any connector directly but might rely on some other module that uses their own connector.s (eg a Modal-View, which uses a Menu, which uses a function to check if the menu entry should be shown which calls the backend and is mocked)

i've found something called moduleNameMapper in jest, but I have no clue how to use it. is this the right way to go? how do I debug it?

My current Jest-Config:

module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'jsdom',
    testPathIgnorePatterns: ['jest-setup.spec.ts'],
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
    moduleNameMapper: {
        '@/(.*)$': '<rootDir>/$1',
        // '.\\/connector': './connector.mocked.ts', // does not work
    },
    setupFilesAfterEnv: ['<rootDir>/jest-setup.spec.ts'],
};

You need to swap the order of your keys in moduleNameMapper . So it becomes something like this:

moduleNameMapper: {
    '@/(.*)connector(.ts)?$': '<rootDir>/$1connector.mock',
    '@/(.*)$': '<rootDir>/$1'
}

Then in your screen you do

import { something } from '@/connector'

something() // live connector

but your spec files will import @/connector.mock and something() will do the mocked stuff.

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