nestjs单元测试指南
孙泽辉 Lv5

刚刚接触测试,发现坑太多了,有必要记录一下。

测试效果:

image

配置测试环境

我的项目是使用@nest/cli创建的,它只有一个app.controller.spec.ts,但是引入我写的module就会报很多错

路径别名

首先解决tsconfig.ts的路径别名问题,如果你在app.module.ts中写了路径别名,那么jest处理不了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { UserModule } from '@/user/user.module';
// 报错
/*
FAIL src/user/test/user.controller.spec.ts
● Test suite failed to run

Cannot find module '@/user/entities/user.entity' from 'user/test/user.controller.spec.ts'

1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { TypeOrmModule } from '@nestjs/typeorm';
> 3 | import { User } from '@/user/entities/user.entity';
| ^
4 | import { UserController } from '../user.controller';
5 | import { UserService } from '../user.service';
6 | import connectionCfg from '@/config/database';

at Resolver._throwModNotFoundError (../node_modules/.pnpm/jest-resolve@28.1.1/node_modules/jest-resolve/build/resolver.js:491:11)
at Object.<anonymous> (user/test/user.controller.spec.ts:3:1)

Test Suites: 1 failed, 1 passed, 2 total */

解决方法:在package.jsonjest配置中,添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// package.json
{
"name": "examination",
"version": "0.0.1",
"description": "",
"author": "",
"dependencies": {
},
"devDependencies": {
},
// !!!!!!!!!!!!!!!!!!!!!!!!!!!
"jest": {
"rootDir": "src",
"moduleNameMapper": {
"@/(.*)$": "<rootDir>/$1"
},
// ...
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!
}

配置typeorm

typeorm的配置也要一并添加进test中

这是我的user.controller.spec.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { Test, TestingModule } from '@nestjs/testing';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from '@/user/entities/user.entity';
import { UserController } from '../user.controller';
import { UserService } from '../user.service';
import connectionCfg from '@/config/database';

describe('AppController', () => {
let userController: UserController;

beforeEach(async () => {
// 这里注入 User,和配置文件
const user: TestingModule = await Test.createTestingModule({
imports: [
TypeOrmModule.forRoot({ ...connectionCfg, entities: [User] }),
TypeOrmModule.forFeature([User]),
],
controllers: [UserController],
providers: [UserService],
exports: [UserService],
}).compile();

userController = user.get<UserController>(UserController);
});

describe('register', () => {
it('should register!"', async () => {
const res = await userController.register({
username: 'sunzehui',
password: 'sunzehui',
});
console.log(res);
});
});
});

注意配置文件要把原有的entities替换成自己手动导入的,因为之前是从dist拿的,现在拿不到。

 Comments
Comment plugin failed to load
Loading comment plugin
Powered by Hexo & Theme Keep
Total words 85.5k