【问题标题】:Unexpected behavior from Jest mockImplementation来自 Jest mockImplementation 的意外行为
【发布时间】:2021-03-31 13:10:38
【问题描述】:

我有代码要编写测试以供以后重构,因此我无法更改代码或任何依赖项。问题来了:

// foo.js
Knex = require('knex')

module.exports ={func}
// calling this inside func will 
// have the expected {a:4}
client = Knex()


async function func(){
  console.log(client)
  return true
}
// foo.spec.js
const foo = require('./foo')
const Knex = require('knex')
jest.mock('knex', ()=>jest.fn())

describe('jest.mockImplementation',()=>{
  it('should mock knex',async ()=>{
    Knex.mockImplementation(()=>({a:4}))
    // alternative, I can put
    // const foo = require('./foo')
    // here
    await foo.func()
  })
})
// jest.config.js
module.exports={
  "verbose": true,
  "testEnvironment": "node",
}
//package.json
{
  "dependencies": {
    "jest": "^26.6.3",
    "knex": "0.19.3"
  }
}

我跑: $ jest --config jest.config.js --runInBand foo.spec.js,我希望有一个{ a : 4} 的控制台日志,但它是undefined。但是请注意,如果我将client 移动到func 中,那么它将记录{a : 4}

或者,如果我将client 保留在原处,将require foo 留在spec.jsmockImplementation 之后,它将再次具有预期的控制台日志。

我本来希望看到clientfunc 之外创建的正确行为,而无需在mockImplementation 之后创建require foo

为什么会发生这种情况?如何在不移动 client 的情况下获得所需的行为?还有requireing里面的函数也不是最好的。

我创建了这个 repl.it 用于实验;请不要更新它以供他人使用:

https://replit.com/join/xmlwttzl-eminarakelian1

【问题讨论】:

    标签: javascript node.js jestjs


    【解决方案1】:

    模块作用域的代码在需要模块时会立即执行,所以在测试用例中提供mock实现已经来不及了。

    jest.mock() 将被提升到测试文件的顶部。它会在require语句之前执行,所以当需要模块时,会使用jest.mock()中提供的mock实现。

    jest.mock() 中提供一个模拟实现,如下所示:

    const foo = require('./foo');
    
    jest.mock('knex', () => jest.fn(() => ({ a: 4 })));
    
    describe('jest.mockImplementation', () => {
      it('should mock knex', async () => {
        await foo.func();
      });
    });
    

    测试结果:

     PASS  examples/66881537/foo.spec.js (6.347 s)
      jest.mockImplementation
        ✓ should mock knex (15 ms)
    
      console.log
        { a: 4 }
    
          at Object.<anonymous> (examples/66881537/foo.js:8:11)
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        6.789 s
    

    【讨论】:

      猜你喜欢
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多