【发布时间】:2021-10-31 14:27:14
【问题描述】:
我有一个带有两个函数的 TypeScript 模块:foo() 调用 bar()。我想模拟 bar() 并从单元测试中调用 foo() 。我试过这个:
foo.ts:
export function bar(){
throw 'not implemented'
}
export function foo(){
return bar();
}
foo.test.ts:
import * as foo from './foo'
test('TODO', () => {
jest.spyOn(foo, 'bar').mockReturnValue('quux')
expect(foo.foo()).toBe('quux')
});
但我得到了一个错误:
FAIL ./foo.test.ts
✕ TODO (4 ms)
● TODO
thrown: "not implemented"
1 | import * as foo from './foo'
2 |
> 3 | test('TODO', () => {
| ^
4 | jest.spyOn(foo, 'bar').mockReturnValue('quux')
5 | expect(foo.foo()).toBe('quux')
6 | });
at Object.<anonymous> (foo.test.ts:3:1)
at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
似乎 foo() 以某种方式绕过了模拟。我怎样才能让它使用模拟而不是真正的 bar()?
【问题讨论】:
标签: typescript jestjs mocking