用jest测试打印脚本中的私有方法

rseugnpd  于 2023-02-27  发布在  Jest
关注(0)|答案(2)|浏览(207)

在下面的代码中,我的测试用例按预期通过,但我使用斯特赖克进行变异测试,handleError函数在变异测试中存活,因此我想通过测试handleError函数是否被调用来杀死变异体。需要帮助测试私有函数。
我试过spyOn,但没有工作

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)
    }
  });
});
wmtdaxz3

wmtdaxz31#

看起来您希望验证在build运行时是否调用了handleError
私有方法被编译为普通的JavaScript原型方法,因此您可以使用any类型让spy创建通过TypeScript类型检查。
下面是一个高度简化的示例:

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!
  });
});
db2dz4w8

db2dz4w82#

给你

const handleErrorSpy = jest.spyOn(OrderBuilder.prototype  as unknown as keyof typeof OrderBuilder, 'handleError');

相关问题