gpt4 book ai didi

node.js - loopback 4中如何编写单元测试用例

转载 作者:行者123 更新时间:2023-12-05 05:48:04 25 4
gpt4 key购买 nike

我是 loopback 4 的新手。我想为我的项目编写单元测试用例。但是,我找不到他们使用模拟服务和使用 stub 的适当示例。

请协助我或分享任何正确编写的单元测试示例(使用模拟服务和 stub )。

谢谢

下面是我的代码库:

Controller

export class CaptureController {
constructor(
@inject(RestBindings.Http.RESPONSE) private response: Response,
@service(HelperService) private helperService: HelperService,
) { }
@post('/capture', {
'x-controller-name': CaptureSwagger.controller,
summary: CaptureSwagger.summary,
description: CaptureSwagger.description,
responses: {
'200': CaptureSuccess.response,
'400': CommonHttpErrors(Messages.badRequest, 400, ''),
'401': CommonHttpErrors(
Messages.unauthorized,
401,
Messages.unauthorized,
),
},
})
async capture(
@requestBody() body: Capture,
): Promise<Response> {
const response = await this.helperService
.getGatewayService()
.capture(body);
const data = this.helperService.getGatewayKeys(
response,
TransactionType.COMPLETE,
);

const buildResponse = BuildResponse.prepare({data});
return this.response.json(buildResponse);
}
}

HelperService

@injectable({scope: BindingScope.TRANSIENT})
export class HelperService {
constructor(
@inject(RestBindings.Http.CONTEXT) private context: RequestContext,
@service(ConvergeService) private convergeService: ConvergeService,
) { }
getGatewayService() {
const merchantGateway: MerchantGateway =
this.context.getSync('merchantGateway');
const gatewayName: PaymentGateway | string = merchantGateway?.sysName
? merchantGateway.sysName
: '';
switch (gatewayName.toLowerCase()) {
case PaymentGateway.CONVERGE:
return this.convergeService;
default:
return this.nexioService;
}
}
}

融合服务

@injectable({scope: BindingScope.TRANSIENT})
export class ConvergeService {
/**
* Capture
* @param body Capture payment
*/
public capture = async (body: Capture) => {
const startAt = process.hrtime();
let errorResp = '';
const captureXml = `${this.xmlData}<ssl_transaction_type>cccomplete</ssl_transaction_type>
<ssl_amount>${body.data.amount}</ssl_amount>
<ssl_txn_id>${body.id}</ssl_txn_id>
</txn>`;
try {
const resp: {data: string} = await axiosApi.post(
`${this.convergeObj.apiUrl}`,
captureXml,
);
const jsonResp = this.parseXmlToJson(resp.data);

if (jsonResp?.txn?.errorCode) {
errorResp = resp.data;
throw new ResponseError.BadRequest(jsonResp.txn.errorMessage);
}
return jsonResp.txn ? jsonResp.txn : jsonResp;
} catch (err) {
this.commonService.getErrorResponse(err);
}
};
}

最佳答案

我将分享一个示例。我认为您可以为您的服务定制它。我们假设,我们有这样的汽车服务和简单​​的价格计算器功能:

@injectable({scope: BindingScope.TRANSIENT})
export class CarService {
constructor(
@repository(CarRepository)
private carRepository: CarRepository,
) {}

async calculateCarPricesWithTaxes(tax: number): Promise<[]> {
const cars = await this.carRepository.find({where: {price: {gte: 10000}}});

return cars.map(car => (car.price * tax / 100) + car.price);
}
}

这个服务的单元测试类是这样的:

describe('CarService', () => {  

let carRepository: StubbedInstanceWithSinonAccessor<CarRepository>;

beforeEach(() => {
carRepository = createStubInstance(CarRepository);

carService = new CarService(carRepository);
});

after(() => {
sinon.restore();
});

describe('calculateCarPricesWithTaxes', () => {
it('should get new prices for cars', async () => {
const find = carRepository.stubs.find;
find.resolves([
{id: 1, price: 10000},
{id: 1, price: 20000},
]);

const res = await carService.calculateCarPricesWithTaxes(10);

expect(res).to.eql([11000, 22000]);
// expect(res).to.not.eql([110, 220]);

sinon.assert.calledWith(find, {where: {price: {gte: 10000}}});

// sinon.assert.calledOnce(find);
});
});
});

希望对你有帮助

关于node.js - loopback 4中如何编写单元测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70874372/

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