gpt4 book ai didi

unit-testing - 单元测试 Nestjs Mongoose 服务

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

我一直在努力弄清楚如何对 NestJS 服务进行单元测试。所以我写了一个规范文件来测试这些使用 mongoose 和 jest 的 NestJS 服务。

spec文件如下:

import { Test, TestingModule } from '@nestjs/testing';
import { EventsService } from './events.service';
import { getModelToken } from '@nestjs/mongoose';
import { CreateEventDto } from './dto/create-event.dto';

const event = {
_id: '53d53d2s',
name: 'Event Name',
description: 'Description of the event.',
min_team_size: 0,
max_team_size: 4,
event_price: 300,
};

describe('EventsService', () => {
let service: EventsService;
const eventModel = {
save: jest.fn().mockResolvedValue(event),
find: jest.fn().mockResolvedValue([event]),
findOne: jest.fn().mockResolvedValue(event),
findOneAndUpdate: jest.fn().mockResolvedValue(event),
deleteOne: jest.fn().mockResolvedValue(true),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
EventsService,
{
provide: getModelToken('Event'),
useValue: eventModel,
},
],
}).compile();

service = module.get<EventsService>(EventsService);
});

it('should return all the events', () => {
expect(service.findAll()).resolves.toEqual([event]).catch( err => {
console.log(err);
});
});
it('should create a new event and save it', () => {
expect(service.create({
name: event.name,
description: event.description,
event_price: event.event_price,
max_team_size: event.max_team_size,
min_team_size: event.min_team_size
} as CreateEventDto )).resolves.toEqual(event).catch(err => {
console.log(err);
});
});
it('should return one event', () => {
expect(service.findOne('53d53d2s')).resolves.toEqual(event).catch(err => {
console.log(err);
});
});
it('should find and update one model', () => {
expect(service.findOneAndUpdate('53d53d2s', {} as any)).resolves.toEqual(event).catch( err => {
console.log(err);
});
});
it('should delete one model', () => {
expect(service.deleteOne('53d53d2s')).resolves.toBeTruthy().catch( err => {
console.log(err);
});
});
});

这是服务文件:

import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { CreateEventDto } from './dto/create-event.dto';
import { EventInterface } from './interfaces/event.interface';
import { InjectModel } from '@nestjs/mongoose';

@Injectable()
export class EventsService {
constructor(@InjectModel('Event') private readonly eventModel: Model<EventInterface>) {}

async create(createEventDto: CreateEventDto): Promise<EventInterface> {
const createdEvent = new this.eventModel(createEventDto);
return createdEvent.save();
}

async findAll(): Promise<EventInterface[]> {
return this.eventModel.find();
}

async findOne(id): Promise<EventInterface> {
return this.eventModel.findOne({ _id: id });
}

async findOneAndUpdate(id, createEventDTO: CreateEventDto): Promise<EventInterface> {
return this.eventModel.findOneAndUpdate({ _id: id }, createEventDTO);
}
async deleteOne(id): Promise<any> {
return this.eventModel.deleteOne({ _id: id});
}
}

除了 create() 之外,这里所有测试都成功通过。它显示以下错误:{ 错误:expect(received).resolves.toEqual()

Received promise rejected instead of resolved
Rejected to value: [TypeError: this.eventModel is not a constructor]
at expect (/home/rakesh/SJPUC/Equinox-2019/equinox-api/node_modules/expect/build/index.js:138:15)
at Object.it (/home/rakesh/SJPUC/Equinox-2019/equinox-api/src/events/events.service.spec.ts:44:5)
at Object.asyncJestTest (/home/rakesh/SJPUC/Equinox-2019/equinox-api/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:102:37)
at resolve (/home/rakesh/SJPUC/Equinox-2019/equinox-api/node_modules/jest-jasmine2/build/queueRunner.js:43:12)
at new Promise (<anonymous>)
at mapper (/home/rakesh/SJPUC/Equinox-2019/equinox-api/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
at promise.then (/home/rakesh/SJPUC/Equinox-2019/equinox-api/node_modules/jest-jasmine2/build/queueRunner.js:73:41)
at process._tickCallback (internal/process/next_tick.js:68:7)
matcherResult: undefined,

另外,我想知道对这些服务进行单元测试的更好方法。

最佳答案

问题是,NesjJS 会将您在测试文件中定义的eventModel 对象注入(inject)到EventService 中。因为它是一个对象,所以它没有构造函数。您可以像这样传递一个类,而不是一个对象:

class EventModel {
constructor(private data) {}
save = jest.fn().mockResolvedValue(this.data);
static find = jest.fn().mockResolvedValue([event]);
static findOne = jest.fn().mockResolvedValue(event);
static findOneAndUpdate = jest.fn().mockResolvedValue(event);
static deleteOne = jest.fn().mockResolvedValue(true);
}

describe('EventsService', () => {
let service: EventsService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
EventsService,
{
provide: getModelToken('Event'),
useValue: EventModel,
},
],
}).compile();

...

关于unit-testing - 单元测试 Nestjs Mongoose 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57007200/

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