节点版本: v10.13.0
我正在尝试对NodeJS请求并发性进行非常简单的测试,包括繁重的CPU计算.我理解NodeJS不是CPU绑定进程的最佳工具,并且不应系统地生成子进程,但此代码是为了测试子进程的工作原理.这也是使用NestJS用TypeScript编写的.
SRC/app.controller.ts
import { Get, Param, Controller } from '@nestjs/common';
import fork = require('child_process');
@Controller()
export class AppController {
@Get()
async root(): Promise<string> {
let promise = new Promise<string>(
(resolve, reject) => {
// spawn new child process
const process = fork.fork('./src/cpu-intensive.ts');
process.on('message', (message) => {
// when process finished, resolve
resolve( message.result);
});
process.send({});
}
);
return await promise;
}
}
Run Code Online (Sandbox Code Playgroud)
SRC/CPU-intensive.ts
process.on('message', async (message) => {
// simulates a 10s-long process
let now = …Run Code Online (Sandbox Code Playgroud) TLNR:我试图在控制器规范中而不是在 e2e 规范中测试 DTO 验证,后者正是为此而设计的。McDoniel 的回答为我指明了正确的方向。
我开发了一个 NestJS 入口点,如下所示:
@Post()
async doStuff(@Body() dto: MyDto): Promise<string> {
// some code...
}
Run Code Online (Sandbox Code Playgroud)
我使用class-validator这样当我的 API 收到请求时,有效负载被解析并转换为 MyDto 对象,并执行作为 MyDto 类中的注释的验证。请注意,MyDto 有一个 MySubDto 类的嵌套对象数组。使用@ValidateNested 和@Type 注释,嵌套对象也可以正确验证。
这很好用。
现在我想为执行的验证编写测试。在我的 .spec 文件中,我写道:
import { validate } from 'class-validator';
// ...
it('should FAIL on invalid DTO', async () => {
const dto = {
//...
};
const errors = await validate( dto );
expect(errors.length).not.toBe(0);
}
Run Code Online (Sandbox Code Playgroud)
这将失败,因为经过验证的 dto 对象不是 MyDto。我可以这样重写测试:
it('should FAIL on invalid DTO', …Run Code Online (Sandbox Code Playgroud)