首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在NestJS e2e测试中获取猫鼬实例

在NestJS e2e测试中获取猫鼬实例
EN

Stack Overflow用户
提问于 2020-05-15 20:19:39
回答 2查看 1.1K关注 0票数 5

我开始为我的e2e API编写NestJS测试,我想使用一个测试数据库。我在测试模块中导入了MongooseModule,它正确地使用了预期的测试数据库。

然后,我想清除收集和重新插入夹具之前,我的测试。为了做到这一点,我想使用NestJS使用的Mongoose实例。但是我没有成功,最终创建了第二个连接(在beforeAll钩子中)

我还没有找到任何办法来避免这种情况。

以下是代码:

代码语言:javascript
复制
describe('Color', () => {
  let app: INestApplication
  let db: Connection

  beforeAll(async () => {
    db = await mongoose.createConnection(process.env.MONGO_TEST_URL, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true
    })

    db.model('Color', ColorSchema)
  })

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [
        MongooseModule.forRoot(process.env.MONGO_TEST_URL, {
          useCreateIndex: true,
          useFindAndModify: false
        }),
        AppModule
      ]
    }).compile()

    await db.model('Color').deleteMany({})
    await db.model('Color').insertMany(ColorFixtures)

    app = moduleFixture.createNestApplication()
    await app.init()
  })

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

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .post('/graphql')
      .send({
        operationName: 'findAll',
        query: 'query findAll { colors { id name } }',
        variables: {}
      })
      .expect(200)
      .expect({})
  })
})

有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2022-01-18 14:55:14

我编写了自己的身份验证( e2e )测试(/signup)示例:

afterEach是从学院中删除数据的好地方。

代码语言:javascript
复制
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { AppModule } from './../src/app.module';
import { Connection } from 'mongoose';
import { getConnectionToken } from '@nestjs/mongoose';
import { SignupUserDto } from '../src/authentication/dto/signup-user.dto';
import { UsersService } from '../src/users/users.service';

describe('Authentication (e2e)', () => {
  let app: INestApplication;
  let connection: Connection;
  let usersService: UsersService;
  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    usersService = moduleFixture.get<UsersService>(UsersService);
    //connection = await moduleFixture.get(getConnectionToken());
    app = moduleFixture.createNestApplication();
    await app.init();
  });
  afterAll(async () => {
    // await connection.close(/*force:*/ true); // <-- important
    await app.close();
  });

  afterEach(async () => {
    // truncate data from DB...
    await usersService.removeAll();
  });
  describe('POST /signup', () => {
    const signupData: SignupUserDto = {
      email: 'testd@test.com',
      name: 'testuser',
      password: 'test123456',
    };

    it('should return 400 error if all inputs not provided', () => {
      let data = { ...signupData };
      delete data['password'];
      return request(app.getHttpServer())
        .post('/auth/signup')
        .send(data)
        .expect(400);
    });

    it('should return 400  if email is in use', async () => {
      await usersService.create(signupData);
      return request(app.getHttpServer())
        .post('/auth/signup')
        .send(signupData)
        .expect(400);
    });
  });
});

并在app.module.ts中设置db连接。

代码语言:javascript
复制
@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      cache: true,
    }),
    MongooseModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        uri:
          config.get('NODE_ENV') === 'test'
            ? config.get<string>('MONGO_TEST_CONNECTION')
            : config.get<string>('MONGO_CONNECTION'),
        autoIndex: false,
      }),
    }),
    // add throttle based on api (REST,Graphql,Socket,...)
    UsersModule,
    AuthenticationModule,
  ]
  ,...
  });
票数 0
EN

Stack Overflow用户

发布于 2022-11-23 03:29:36

我所做的就是使用moduleFixture从IoC中获取模型。

看起来会是这样的。

代码语言:javascript
复制
const colorModel: Model<ColorDocument> = moduleFixture.get('ColorModel');
await colorModel.deleteMany({})
await colorModel.insertMany(ColorFixtures)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61827702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档