简体   繁体   English

使用 nestjs 进行 supertest e2e:请求不是函数

[英]supertest e2e with nestjs: request is not a function

I try to introduce e2e tests for my simple NestJS backend services.我尝试为我的简单 NestJS 后端服务引入 e2e 测试。 I am providing a custom userService and a custom UserRepository mocked with sinon.我提供了一个自定义的 userService 和一个用 sinon 模拟的自定义 UserRepository。

This is my user.e2e-spec.ts file:这是我的user.e2e-spec.ts文件:

import * as request from 'supertest';
import * as sinon from 'sinon';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { UserService } from '../../src/user/user.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { User } from '../../src/user/user.entity';
import { TestUtil } from '../../src/utils/TestUtil';
import { createFakeUser } from '../../src/user/test/userTestUtil';

let sandbox: sinon.SinonSandbox;
let testUtil;

describe('User', () => {
    let app: INestApplication;
    const fakeUser = createFakeUser();
    const userService = { findOne: () => fakeUser };

    beforeAll(async () => {
        sandbox = sinon.createSandbox();
        testUtil = new TestUtil(sandbox);
        const module = await Test.createTestingModule({
            providers: [
                {
                    provide: UserService,
                    useValue: userService,
                },
                {
                    provide: getRepositoryToken(User),
                    useValue: testUtil.getMockRepository().object,
                },
            ],
        }).compile();

        app = module.createNestApplication();
        await app.init();
    });

    it(`/GET user`, () => {
        return request(app.getHttpServer())
            .get('/user/:id')
            .expect(200)
            .expect({
                data: userService.findOne(),
            });
    });

    afterAll(async () => {
        await app.close();
    });
});

and this is my user.controller.ts :这是我的user.controller.ts

import { ApiBearerAuth, ApiUseTags } from '@nestjs/swagger';
import { Controller, Get, Param } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './user.entity';

@ApiUseTags('Users')
@ApiBearerAuth()
@Controller('user')
export class UserController {
    constructor(private readonly userService: UserService) {}

    @Get('/:id')
    findOne(@Param('id') id: number): Promise<User> {
        return this.userService.find(id);
    }
}

I wrote a bunch of Unit tests with the same pattern and it works.我用相同的模式编写了一堆单元测试并且它有效。 Have no clue what is wrong with this e2e supertest.不知道这个 e2e 超级测试有什么问题。

Thanks for your help!谢谢你的帮助!

UPDATE : This is the error message I get:更新:这是我收到的错误消息:

TypeError: request is not a function
    at Object.it (/Users/florian/Development/Houzy/nestjs-backend/e2e/user/user.e2e-spec.ts:40:16)
    at Object.asyncFn (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/jasmine_async.js:124:345)
    at resolve (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/queue_runner.js:46:12)
    at new Promise (<anonymous>)
    at mapper (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/queue_runner.js:34:499)
    at promise.then (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/queue_runner.js:74:39)
    at <anonymous>

Change import of request to:将请求的导入更改为:

import request from 'supertest';

In your test, replace :id with number:在您的测试中,将 :id 替换为数字:

it(`/GET user`, () => {
        return request(app.getHttpServer())
            .get('/user/1') // pass here id, not a string
            .expect(200)
            .expect({
                data: userService.findOne(),
        });
});

And in controller:在控制器中:

 @Get('/:id')
    findOne(@Param('id') id: number): Promise<User> {
        return this.userService.find(id);
 }

This should work now.这现在应该可以工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 e2e 如何与 guard nestjs - How e2e with guard nestjs 在e2e测试期间,NestJS cookie-parser不是函数错误 - NestJS cookie-parser is not a function error during e2e test 使用 NestJS、Mysql 和 Passport 模块上的 TypeORM 进行单元和 e2e 测试 - Unit and e2e testing with NestJS, TypeORM on Mysql and Passport module NestJs e2e 返回 201 创建的响应,但缺少所需的表单数据,预计 400 错误请求 - NestJs e2e returns 201 created response though required form data is missing, expected 400 bad request 巢穴 | e2e 测试 | 在 ConfigModule 触发验证之前“走私/注入”自定义环境变量 - Nestjs | e2e testing | "smuggle/inject" custom environment variables before ConfigModule triggers validation 由于 redis 和 mongodb 随机连接错误,nestjs e2e 测试失败 - nestjs e2e tests failed because of redis and mongodb connection error randomly 测试执行因源自 Hammerhead 的请求管道的问题而随机中止(Testcafe e2e 测试) - Test execution randomly aborted by an issue originated in the request-pipeline of Hammerhead (Testcafe e2e tests) 使用 ng e2e 进行量角器调试 - Protractor debugging using ng e2e 单元和 e2e 测试 grpc 微服务 - Unit and e2e testing a grpc microservice 文件替换不适用于 e2e 测试 - Filereplacements not working for e2e testing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM