首页 > 解决方案 > 如何在端到端(e2e)测试中模拟嵌套 typeorm 数据库模块?

问题描述

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

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

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

你可以在这里玩代码我的代码

标签: databasepostgresqlmockingnestjstypeorm

解决方案


在 cat.module.ts 中的 app.module.ts TypeOrmModule.forRoot() 和 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();
    });

我可以回答任何问题


推荐阅读