NestJS 官方文档很好,但是却不能面面俱到,单元测试就是其中之一,当我使用typeORM框架后测试用例都跑不起来啦,各种 error。。。😢
你是否也碰到同样的问题呢
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from './users.service';
import { Repository } from 'typeorm';
import { Users } from './users.entity';
import { USERS_REPOSITORY_TOKEN } from './../constants/constants';
import { Type, HttpException } from '@nestjs/common';
import { AppModule } from '../app.module';
import { async } from 'rxjs/internal/scheduler/async';
import { Logger } from '@nestjs/common';
import { ParameterException } from '../common/parameter.exception';
describe('UsersService', () => {
let service: UsersService;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [AppModule],/// 导入主模块 是因为数据库配置在主模块中
providers: [
UsersService, // 要测试的服务
{
provide: Users, // 操作的数据模型
useClass: Repository,
},
],
}).compile(); // 创建用户测试测试模块
service = module.get<UsersService>(UsersService); //在测试模块中获取 userService
});
it('查询所有用户信息', async () => {
const users = await service.findAll({
name: 'name',
});
expect(users.length).toBe(users.length);
});
it('注册新增用户信息', async () => {
const users = await service.register({
name: 'name',
email: '***@qq.com',
nick: '****',
password: '****',
phone: '18516512667',
});
expect(users.id).toBeGreaterThan(0);
});
it('用户登陆', async () => {
const users = await service.login({
name: '****',
password: '****',
});
expect(users.name).toBe('name');
});
});