用玩笑测试打字稿中的私有功能 [英] testing private functions in typescript with jest

查看:48
本文介绍了用玩笑测试打字稿中的私有功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我的测试用例按预期方式通过了,但是我正在使用stryker进行突变测试,handleError函数在突变测试中仍然存在,因此我想通过测试是否调用handleError函数来杀死突变体.需要帮助测试私有功能.

In the below code my test case was passed as expected but i am using stryker for mutation testing , handleError function is survived in mutation testing , so i want to kill the mutant by testing the handleError function is being called or not. need to help to test the private function.

我尝试了spyOn但没有用

i tried spyOn but didn't work

const orderBuilderSpy = jest.spyOn(orderBuilder, 'build')
const handleError = jest.fn()
expect(rderBuilderSpy).toHaveBeenCalledWith(handleError)

// code written in nestJS/typescript

export class OrderBuilder {
  private amount: number

  public withAmount(amount: number): BuyOrderBuilder {
    this.amount = amount
    return this
  }


  public build(): TransactionRequest {
    this.handleError()
    return {
      amount: this.amount,
      acceptedWarningRules: [
        {
          ruleNumber: 4464
        }
      ]
    }
  }
  private handleError() {
    const errors: string[] = []
    const dynamicFields: string[] = [
      'amount',
    ]
    dynamicFields.forEach((field: string) => {
      if (!this[field]) {
        errors.push(field)
      }
    })
    if (errors.length > 0) {
      const errorMessage = errors.join()
      throw new Error(`missing ${errorMessage} field in order`)
    }
  }

}


// test
describe('Order Builder', () => {
  it('should test the handleError', () => {
    const orderBuilder = new OrderBuilder()
    const errorMessage = new Error(
      `missing amount field in order`
    )
    try {
      orderBuilder.build()
    } catch (error) {
      expect(error).toEqual(errorMessage)
    }
  });
});

推荐答案

您似乎想验证handleError在运行时是否被调用.

It looks like you are wanting to verify that handleError gets called when build runs.

私有方法被编译为普通的JavaScript原型方法,因此您可以使用any类型来让间谍创建通过TypeScript类型检查.

Private methods are compiled to normal JavaScript prototype methods, so you can use the any type to let the spy creation pass through the TypeScript type checking.

这是一个高度简化的示例:

Here is a highly simplified example:

class OrderBuilder {
  public build() {
    this.handleError()
  }
  private handleError() {
    throw new Error('missing ... field in order')
  }
}

describe('Order Builder', () => {
  it('should test the handleError', () => {
    const handleErrorSpy = jest.spyOn(OrderBuilder.prototype as any, 'handleError');
    const orderBuilder = new OrderBuilder()
    expect(() => orderBuilder.build()).toThrow('missing ... field in order');  // Success!
    expect(handleErrorSpy).toHaveBeenCalled();  // Success!
  });
});

这篇关于用玩笑测试打字稿中的私有功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆