【问题标题】:How can I mock nest typeorm database module in end to end (e2e) tests?如何在端到端(e2e)测试中模拟嵌套 typeorm 数据库模块?
【发布时间】:2020-02-09 03:37:30
【问题描述】:

全部。 包括有关您的目标的详细信息: 我正在尝试在 e2e 测试中模拟存储库

描述预期和实际结果: 对服务器的请求将无法访问持久层。我们应该模拟连接和存储库。

我已更新代码,但存储库仍未被覆盖。 也许我需要通过 Facade 提供者来实现它

你可以在这里玩代码My code

【问题讨论】:

    标签: database postgresql mocking nestjs typeorm


    【解决方案1】:

    您可以使用TypeORM fixtures,它们允许您在开发或测试代码时创建夹具/假数据。

    npm install typeorm-fixtures-cli --save-dev
    

    fixture 可以用 YAML 文件表示。例如:

    entity: User
    items:
      user{1..10}:
        username: bob
        fullname: Bob
        birthDate: 1980-10-10
        email: bob@example.org
        favoriteNumber: 42
    

    该库集成了Faker,以帮助生成虚假数据,例如姓名、电子邮件地址、电话号码……等。您还可以在不同的灯具之间建立关系。

    之后,您可以加载固定装置并将它们与 TypeORM 一起使用。

    const loadFixtures = async (fixturesPath: string) => {
      let connection;
    
      try {
        connection = await createConnection();
        await connection.synchronize(true);
    
        const loader = new Loader();
        loader.load(path.resolve(fixturesPath));
    
        const resolver = new Resolver();
        const fixtures = resolver.resolve(loader.fixtureConfigs);
        const builder = new Builder(connection, new Parser());
    
        for (const fixture of fixturesIterator(fixtures)) {
          const entity = await builder.build(fixture);
          await getRepository(entity.constructor.name).save(entity);
        }
      } catch (err) {
        throw err;
      } finally {
        if (connection) {
          await connection.close();
        }
      }
    };
    

    您可以将它与内存中的 SQLLite 数据库结合使用。只需让 TypeORM 根据实体元数据生成数据库。使用fixture将假数据加载到内存数据库中,然后运行你的测试。

    【讨论】:

    • 谢谢。我觉得不符合我的要求。来自nestjs 支持的@jmcdo29 帮助我在e2e 测试中模拟repo。稍后我会把好的分辨率放在这里
    • @VasiliyIvanov 我也有类似的问题,你能分享一下你的解决方案吗?
    【解决方案2】:

    在 app.module.ts 中使用 TypeOrmModule.forRoot() 和cats.module.ts中的TypeOrmModule.forFeature([CatEntity])

     import { getRepositoryToken } from '@nestjs/typeorm';
    
    
     beforeEach(async () => {
            const module: TestingModule = await Test.createTestingModule({
                // import modules, the modules should import the entities they deal with.
                // The testing module should be barebones
                imports: [
                    // basically looks like a unit test but goes through the HTTP motions
                    // if you want to include the AppModule you'll need to create a configuration
                    // for the database module (TypeORM) that will be accessible in a testing context
                    // AppModule,
                    CatModule,
                ],
            })
                // this is for overriding a provider that exists in a module already (such as the ProjectsModule)
                .overrideProvider(getRepositoryToken(ProjectEntity))
                // this is how you give the factory, value, or class to use instead
                .useFactory({
                    factory: () => ({
                        create: jest.fn(() => new Promise((resolve) => resolve(cat))),
                        find: jest.fn(() => new Promise((resolve) => resolve([cat]))),
                        update: jest.fn((id, project2) => new Promise((resolve) => resolve(cat2))),
                        findOne: jest.fn(
                            ({ uuid }) =>
                                new Promise((resolve) => {
                                    resolve(cat);
                                }),
                        ),
                        delete: jest.fn((uuid) => new Promise((resolve) => resolve())),
                        save: jest.fn(
                            (data) =>
                                new Promise((resolve) => {
                                    // data = data.uuid === undefined ? data.uuid = uuid() : data;
                                    resolve(data);
                                }),
                        ),
                    }),
                })
                .compile();
            app = module.createNestApplication();
    
            await app.init();
        });
    

    我可以回答任何问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      相关资源
      最近更新 更多