【问题标题】:How to drop database in Integration Testing mysql TypeOrm Nestjs如何在集成测试 mysql TypeOrm Nestjs 中删除数据库
【发布时间】:2022-08-23 00:11:28
【问题描述】:

我使用mysql作为数据库,我在互联网上搜索,我尝试的方法不是最新的。我希望数据库在每次测试中自行重置。但是我找不到合适的方法,你能帮忙吗?

describe(\'Authentication System\', () => {
  let app: INestApplication;

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

  it(\'if user already in database\', async () => {
    await request(app.getHttpServer())
      .post(\'/auth/signup\')
      .send({name:\"muti\"})
      .expect(HttpStatus.BAD_REQUEST)
      .then((res) => {
        const { access_token } = res.body;
        expect(access_token).not.toBeDefined();
      });
  });

    标签: mysql node.js nestjs


    【解决方案1】:

    我能够通过使用 TypeORM 提供的 DataSource 对象来解决它。

    像这样初始化 DataSource 对象:

    const dataSource = new DataSource({
      type: 'mysql',
      host: process.env.DBHOST,
      port: Number(process.env.DBPORT),
      username: process.env.DBUSER,
      password: process.env.DBPASS,
      database: process.env.DBNAME,
      entities: [`Your Entity Classes`],
      synchronize: true,
    });
    

    确保将适当的配置加载到 app.module.ts 文件中

    然后您可以使用beforeAllafterAll 测试用例分别初始化和删除数据库。

    describe('AppController (e2e)', () => {
      let app: INestApplication;
    
      beforeAll(async () => {
        await dataSource.initialize();
      });
    
      beforeEach(async () => {
        const moduleFixture: TestingModule = await Test.createTestingModule({
          imports: [AppModule],
        }).compile();
    
        app = moduleFixture.createNestApplication();
        await app.init();
      });
    
      it('/ (GET)', () => {
        return request(app.getHttpServer())
          .get('/')
          .expect(HttpStatus.OK)
          .expect('Hello World!');
      });
    
      afterAll(async () => {
        await dataSource.dropDatabase();
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 1970-01-01
      • 2021-09-08
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 2021-08-22
      • 1970-01-01
      相关资源
      最近更新 更多