在下面的代码中,我的测试用例按预期通过,但我使用斯特赖克进行变异测试,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)
}
});
});
2条答案
按热度按时间wmtdaxz31#
看起来您希望验证在
build
运行时是否调用了handleError
。私有方法被编译为普通的JavaScript原型方法,因此您可以使用
any
类型让spy创建通过TypeScript类型检查。下面是一个高度简化的示例:
db2dz4w82#
给你