【问题标题】:Jest SpyOn value instead of getterJest SpyOn 值而不是 getter
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 2017-11-29
    • 2022-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多