[英]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. connector.ts
和connector.mocked.ts
第一个包含“实时”代码,第二个包含一些模拟/虚拟实现。 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
.这将直接在我们的应用程序中执行,或者在故事书中将被重写为
connector.mocked.ts
。 In Storybook this happens in the global config:在 Storybook 中,这发生在全局配置中:
module.exports = {
...
webpackFinal: (config) => {
...
config.resolve.alias = {
...config.resolve.alias,
'./connector': './connector.mocked',
'@': path.resolve(__dirname, '..'),
}
}
}
whats the equivalent in Jest for this? Jest 中的等价物是什么? 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)
我不想为每个测试都写这个,因为被测单元可能不直接使用任何连接器,但可能依赖于使用它们自己的连接器的其他模块(例如,使用菜单的模式视图,它使用一个 function 检查是否应该显示调用后端并被模拟的菜单条目)
i've found something called moduleNameMapper
in jest, but I have no clue how to use it.我开玩笑地发现了一个叫做
moduleNameMapper
的东西,但我不知道如何使用它。 is this the right way to go?这是 go 的正确方法吗? how do I debug it?
我该如何调试它?
My current Jest-Config:我当前的 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
.您需要在
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.但是您的规范文件将导入
@/connector.mock
并且something()
将做模拟的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.