简体   繁体   English

开玩笑不是 mocking 内部 function

[英]jest not mocking internal function

I am having an issue with mocking functions called from within my module.我在从我的模块中调用 mocking 函数时遇到问题。 when the mocked function is called from the test, it works as expected.当从测试中调用模拟的 function 时,它按预期工作。 but when that same mocked function is called from the library, it calls the actual function.但是当从库中调用相同的模拟 function 时,它会调用实际的 function。

I have tried the jest.mock('./myModule', () => {}) approach, and enableAutomock as well, but with the same results.我已经尝试了jest.mock('./myModule', () => {})方法,也尝试了enableAutomock ,但结果相同。

I feel like i have not had this problem in other projects, but have looked through my jest configuration, and don't see anything that would effect it.我觉得我在其他项目中没有遇到过这个问题,但是查看了我的 jest 配置,没有看到任何会影响它的东西。

what am i missing here?我在这里错过了什么? how can i mock functions called internally within my module?我如何模拟模块内部调用的函数?

// myModule.js

export function foo() {
  return 'foo'
}

export function bar() {
  return foo()
}
// myModule.test.js
import * as myModule from './myModule';

jest.spyOn(myModule, 'foo').mockReturnValue('mock foo');

// i have also tried...
// jest.mock('./myModule', () => {
//   ...(jest.requireActual('./myModule')),
//   foo: jest.fn().mockReturnValue('mock foo')
// });

it('should', () => {
  expect(myModule.foo()).toEqual('mock foo'); // PASS: returns 'mock foo'
  expect(myModule.bar()).toEqual('mock foo'); // FAIL: returns 'foo'
});

I found using ts-jest in my jest config, allowed these tests to run as i expected我发现在我的 jest 配置中使用了ts-jest ,允许这些测试按我预期的方式运行

transform: {
  '^.+\\.[tj]sx?$': ['ts-jest'],
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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