【发布时间】:2020-10-14 16:09:31
【问题描述】:
如何模拟在我要测试的类中使用的导入类?
我的代码如下:
Bird.js
export default class Bird {
constructor() {...}
tweet() {...}
}
Nest.js
import Bird from 'Bird.js'
export default class Nest {
spawn() {
this.bird = new Bird()
this.bird.tweet()
}
}
我想测试spawn 是否真的可以调用tweet,所以我想模拟整个Bird 类。我试过了:
Nest.spec.js
jest.mock('<some_path>/Bird.js')
import Nest from '<some_path>/Nest.js'
test('...', () => {
const nest = new Nest()
nest.spawn()
expect(this.bird.tweet).toBeCalledTimes(1)
})
不过,Nest.spawn() 调用了this.bird.tweet(),但似乎jest.mock('<some_path>/Bird.js') 不会影响Nest.js 中的import Bird from 'Bird.js'。
也就是说,它仍然导入原始类,tweet 具有原始行为而不是jest.fn()。
【问题讨论】:
标签: javascript unit-testing mocking jestjs vue-test-utils