开玩笑SpyOn值,而不是吸气剂

时间:2020-01-27 23:41:38

标签: javascript node.js typescript jestjs nestjs

我有这样的功能:

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并返回值,等等。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

在这种情况下,不需要模拟。您可以在null测试用例中,使用SomeOtherClass为其参数it显式创建实例:

it('should throw an error if injected simpleInstance is null', () => {
  myClassInstance = new MyClass(null)
  expect(() => myClassInstance.myGetter).toThrow(Error('Bad thing'))
})