gpt4 book ai didi

typescript - 用 Jest 测试 typescript 中的私有(private)函数

转载 作者:行者123 更新时间:2023-12-04 04:27:59 28 4
gpt4 key购买 nike

在下面的代码中,我的测试用例按预期通过了,但我使用 stryker 进行突变测试,handleError 函数在突变测试中幸存下来,所以我想通过测试是否调用了 handleError 函数来杀死突变体。需要帮助测试私有(private)功能。

我试过 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)
}
});
});

最佳答案

您似乎想要验证 handleErrorbuild 时被调用运行。

私有(private)方法被编译成普通的 JavaScript 原型(prototype)方法,所以你可以使用 any type 让 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!
});
});

关于typescript - 用 Jest 测试 typescript 中的私有(private)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56044471/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com