gpt4 book ai didi

node.js - 服务中的模拟存储库, Node TypeScript

转载 作者:太空宇宙 更新时间:2023-11-04 01:21:08 25 4
gpt4 key购买 nike

我正在尝试进行单元测试,为此我必须模拟 this.orderRepository.findById (id); 方法,该方法接受存储库以通过其 ID 查找对象。返回值已经设置了,但是我无法通过测试。我正在使用 jest 构建单一测试,这是我使用 typescript 在 Node 中进行的第一个测试。

orderService.ts

import { OrderRepository } from '../repository/orderRepository';
import { Service, Inject, } from 'typedi';


@Service()
export default class OrderService {
constructor(
private orderRepository: OrderRepository,
@Inject('logger') private logger
) {}

public async FindById(id: string){
try{
const orderRecord = await this.orderRepository.findById(id);

return orderRecord;
} catch (e) {
this.logger.error(e);
throw e;
}
}

orderRepository.ts

 import {Inject} from 'typedi';

export class OrderRepository {
constructor(
@Inject('orderModel') private orderModel:
Models.OrderModel
) {}

public async findById(id: any) {
return this.orderModel.findById(id);
}

userService.test.ts

import OrderService from '../src/services/order';
import { OrderRepository } from '../src/repository/orderRepository';
import Order from '../src/models/order';

const orderData = {id_product: "564sd654asd5as64d", quantity: 3,
orderStatus: "registeredOrder", deliveryDateResquested: "2019-12-25"};
let orderModel = new Order(orderData);

describe('Order', () => {
let instance: OrderService;
instance = Container.get(OrderService);
var orderRepository: OrderRepository;
var logger;

test('FindById', async () => {
var service = new OrderService(orderRepository, logger);
const spy = OrderRepository.prototype.findById = jest.fn();
spy.mockReturnValue(orderModel);
const result = service.FindById("cenas");
expect(result).toBe(orderModel);

spy.mockRestore();
})

结果测试

  Order
✕ FindById (7ms)

● Order › FindById

expect(received).toBe(expected) // Object.is equality

Expected: {"_id": "5def6ec34bf18833fa2afcb0", "id_product":
"564sd654asd5as64d", "orderStatus": "registeredOrder", "quantity": 3,
"requestDate": 2019-12-10T10:09:07.139Z}
Received: {}

Difference:

- Expected
+ Received

- Object {
- "_id": "5def6ec34bf18833fa2afcb0",
- "id_product": "564sd654asd5as64d",
- "orderStatus": "registeredOrder",
- "quantity": 3,
- "requestDate": 2019-12-10T10:09:07.139Z,
- }
+ Promise {}

22 | spy.mockReturnValue(orderModel);
23 | const result = myclass.FindById("cenas");
> 24 | expect(result).toBe(orderModel);
| ^
25 |
26 | spy.mockRestore();
27 | })

at Object.<anonymous> (tests/userService.test.ts:24:20)

Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 2.718s
Ran all test suites.
npm ERR! Test failed. See above for more details.

最佳答案

我建议你尝试moq.ts图书馆。它使您能够模拟类方法的输入和输出。例如:

const orderRepositoryMock = new Mock<OrderRepository>()
.setup(instance => instance.findById("someID")
.returns(orderModel)
.object()

var service = new OrderService(orderRepositoryMock, logger);
const result = service.FindById("someID");
expect(result).toBe(orderModel); // or assert specific properties

如果您使用mongoose,您可以尝试mock-mongoose库。当调用 mongoose.connect 时,Mockgoose 通过在后面旋转 mongod 来提供测试数据库。默认情况下,它在没有持久性的内存存储中使用。

关于node.js - 服务中的模拟存储库, Node TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59250526/

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