首页 > 解决方案 > 获取QueryFailedError:SQLITE_ERROR:没有这样的表:在测试环境中使用带有typeorm迁移的nestjs时的用户

问题描述

我正在使用nestjs 8并试图让e2e测试与typeorm和迁移一起使用,但我收到了这个错误:

QueryFailedError:SQLITE_ERROR:没有这样的表:用户

当我在 app.module 本身中定义 Typeorm.forRoot() 的主体以使用 configService 运行之前,它正在运行。现在我切换到迁移,我正在使用 ormconfig.js 为开发、测试和生产环境提供一个通用的 ormconfig.js 文件。

ormconfig.js

var dbConfig = {
  synchronize: false,
  migrations: ['migrations/*.js'],
  cli: {
    migrationsDir: 'migrations',
  },
};

switch (process.env.NODE_ENV) {
  case 'development':
    Object.assign(dbConfig, {
      type: 'sqlite',
      database: 'db.sqlite',
      entities: ['**/*.entity.js'],
    });
    break;
  case 'test':
    Object.assign(dbConfig, {
      type: 'sqlite',
      database: 'test.sqlite',
      entities: ['**/*.entity.ts'],
    });
    break;
  case 'production':
    break;
  default:
    throw new Error('Unknown environment provided');
}

module.exports = dbConfig;

package.json -> 脚本

"test:e2e": "cross-env NODE_ENV=test jest --config ./test/jest-e2e.json --maxWorkers=1",
    "typeorm": "cross-env NODE_ENV=development node --require ts-node/register ./node_modules/typeorm/cli.js",
    "typeorm:test": "cross-env NODE_ENV=test node --require ts-node/register ./node_modules/typeorm/cli.js"
...

在 tsconfig.json 中,"allowJs": true属性

app.e2e-spec.ts

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

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

    app = moduleFixture.createNestApplication();
    await app.init();
  });
  
  it('handles a signup request', () => {
    const email = 'bruh@bruh.com';
    return request(app.getHttpServer())
      .post('/auth/signup')
      .send({ email, password: 'password' })
      .expect(201)
      .then((res) => {
        const { id, email } = res.body;
        expect(id).toBeDefined();
        expect(email).toEqual(email);
      });
  });

  it('signup as a new user then get the currently logged in user', async () => {
    const email = 'bruh@bruh.com';
    const res = await request(app.getHttpServer())
      .post('/auth/signup')
      .send({ email, password: 'password' })
      .expect(201);

    const cookie = res.get('Set-Cookie');
    const { body } = await request(app.getHttpServer())
      .get('/auth/whoami')
      .set('Cookie', cookie)
      .expect(200);

    expect(body.email).toEqual(email);
  });
});

要运行的命令:

  1. yarn run typeorm:test migration:generate --name testSchema -o
  2. 纱线运行 typeorm:测试迁移:运行
  3. 纱线运行测试:e2e

结果

第一个命令生成一个迁移文件并根据 ormconfig.js 在根目录中创建 test.sqlite 文件。第二个命令运行迁移文件,它的所有迁移第三个命令应该检测所有实体并显示 e2e 测试的结果,但我得到了上述错误。

这是 nestjs 应用程序的存储库:

https://github.com/JohnLawliet/stephen-nestjs

标签: migrationnestjstypeorm

解决方案


推荐阅读