【发布时间】:2020-05-13 09:05:49
【问题描述】:
我有这样的功能:
class MyClass
constructor(private readonly simpleInstance: SomeOtherClass) {}
get myGetter() {
if(!simpleInstance) {
throw Error('Bad thing')
}
return simpleIntance.id
}
我想写一个测试用例simpleInstance = null
我在模拟 simpleInstance 时遇到了很多麻烦
这是我目前的测试,以及我尝试过的一些选项。
注意:我使用的是
NestJs,因此我的测试中有一个依赖注入模式,为简洁起见,我已将其删除。 TL;DR:初始化的SomeOtherClass在实例化期间被传递到MyClass。
describe('MyClass', () => {
let myClassInstance: MyClass
let someOtherClassMock: jest.Mock<SomeOtherClass>
beforeEach(() => {
someOtherClassMock = jest.fn()
myClassInstance = new MyClass(someOtherClassMock)
})
it('should throw an error if injected simpleInstance is null', () => {
userMock = ........ // <--- Setting up the mocked value is where I have trouble
expect(() => myClassInstance.myGetter).toThrow(Error('Bad thing'))
})
})
我尝试过返回模拟值、监视someOtherClassMock 并返回一个值等。
我该怎么做?
【问题讨论】:
-
为什么不在
it测试用例中调用myClassInstance = new MyClass(null)? -
如果你愿意,你可以回答这个问题,因为这就是我最终要做的。
标签: javascript node.js typescript jestjs nestjs