Jest.js 测试NestJS验证管道不工作

ztmd8pv5  于 2022-12-08  发布在  Jest
关注(0)|答案(2)|浏览(209)

我有一个简单的类,我试图使用NestJS和端到端测试来确保我可以让验证正常工作,但是我不能让验证工作。如果我用Postman或普通客户端发送数据,应用程序会以正确的错误响应。
API.dto.ts

import { IsNumber, IsPositive, IsString } from 'class-validator';
export class ApiDTO {
    @IsString() public readonly FileName:string;
    @IsNumber() @IsPositive() public readonly StatusCode:number;
    @IsNumber() @IsPositive() public readonly TimeOut:number;
}

E2E测试文件

import { Test, TestingModule } from '@nestjs/testing';
import * as request from 'supertest';

import { INestApplication, ValidationPipe } from '@nestjs/common';

import { AppModule } from '@APP/app.module';
import { ApiDTO } from './../../src/api/api.dto';

describe('ApiController (e2e)', () => {
    let app: INestApplication;

    beforeEach(async () => {
        const moduleFixture: TestingModule = await Test.createTestingModule({
            imports: [AppModule],
        }).compile();

        app = moduleFixture.createNestApplication();
        app.useGlobalPipes(new ValidationPipe());
        await app.init();
    });

    it('/api/test/ (POST) test to see data validation works', async done => {
        const RequestBody:ApiDTO = {
            FileName : 'README.md',
            StatusCode: 111,
            TimeOut: -25
        };
        const Expected:string = `${RequestBody.FileName} = ${RequestBody.StatusCode.toString()} after ${RequestBody.TimeOut.toString()}`;

        const ResponseData = await request(app.getHttpServer())
            .post('/api/test')
            .send(RequestBody)
            .set('Accept', 'application/json');

        // All of these will fail as the code returns a 200 OK, as it does not do the validation (TimeOut -25 should fail IsPositive())
        expect(ResponseData.status).toBe(400);
        expect(ResponseData.headers['content-type']).toContain('application/json');

        // This line caused the problem as body is an object
        //expect(ResponseData.body.length).toBeGreaterThan(2);

        expect(ResponseData.body.statusCode).toBe(400);
        expect(ResponseData.body.message[0]).toBe('TimeOut must be a positive number');
        expect(ResponseData.body.error).toBe('Bad Request');
        done();         
    });

});

在进行这个调用时,我得到了一个成功的返回值,200。我的代码应该失败了,因为TimeOut是一个负数,而它应该是IsPositive()。服务和其他代码都在运行,只是没有验证。我已经在beforeEach()中添加了全局管道,所以不确定还需要检查什么。

vu8f3i0k

vu8f3i0k1#

我在测试中发现了这个错误。一旦我将ValidationPipe()添加到应用程序定义中:

app = moduleFixture.createNestApplication();
app.useGlobalPipes(new ValidationPipe());   // <- This addition
await app.init();

这使得验证能够正常运行,测试失败了,因为我正在检查响应主体的长度,

it('/api/test/ (POST) test to see data validation works', async done => {
    ...
    expect(ResponseData.body.length).toBeGreaterThan(10);
    ...
    done();         
});

正文是一个对象,所以对象的.length是无效的。删除这个期望解决了我的问题。

it('/api/test/ (POST) test to see data validation works', async done => {
    const RequestBody:ApiDTO = {
        FileName : 'README.md',
        StatusCode: 111,
        TimeOut: -25
    };
    const Expected:string = `${RequestBody.FileName} = ${RequestBody.StatusCode.toString()} after ${RequestBody.TimeOut.toString()}`;

    const ResponseData = await request(app.getHttpServer())
        .post('/api/test')
        .send(RequestBody)
        .set('Accept', 'application/json');

    expect(ResponseData.status).toBe(400);
    expect(ResponseData.headers['content-type']).toContain('application/json');
    
    expect(ResponseData.body.statusCode).toBe(400);
    expect(ResponseData.body.message[0]).toBe('TimeOut must be a positive number');
    expect(ResponseData.body.error).toBe('Bad Request');
    done();         
});
hfyxw5xn

hfyxw5xn2#

删除我的node_modules文件夹并重新安装它对我很有效。
操作步骤:

  • 删除/node_modules
  • 重新运行npm install

相关问题