问题描述
在下面的代码中,我的测试用例按预期通过,但我使用 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
在 build
运行时是否被调用.
It looks like you are wanting to verify that handleError
gets called when build
runs.
私有方法被编译成普通的 JavaScript 原型方法,所以你可以使用 any
类型让 spy 创建通过 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!
});
});
这篇关于用玩笑测试打字稿中的私有函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!