开玩笑模拟孩子的依赖

and*_*ugh 2 mocking jestjs

我有一个配置文件导入到我将要测试的文件中,我需要能够模拟配置文件,但我似乎做错了什么 - 我有

应用程序.js

import config from './config';
export default class App{
   static get(){
      //refers to config
   }
}
Run Code Online (Sandbox Code Playgroud)

测试文件

import App from './app';  
it('should do something', () => {
   jest.mock(./config, () => {
      return {
         //mocked config
      }
   })
})
Run Code Online (Sandbox Code Playgroud)

但是在运行测试时,我得到的是真实的配置而不是模拟的配置。有任何想法吗?

And*_*rle 6

只需在输入后移动模拟线。

import App from './app';  
jest.mock(./config, () => {
      return {
         //mocked config
      }
})
it('should do something', () => {

})
Run Code Online (Sandbox Code Playgroud)

问题是你App先导入,然后在你的 mock 上导入config,但是在 Jest 中模拟的工作方式就像它用你的模拟替换了被模拟的模块,所以如果你在模拟它的依赖项之前导入一些东西,最终会导入原始而不是模拟版本。

您可能想知道为什么它在我的示例中有效,即使在导入之前没有声明模拟。它的原因 Jest 将mock在编译时提升其作用域块顶部的所有调用。