全。包含关于您的目标的详细信息:我正在尝试在e2e测试中模拟存储库
描述预期和实际结果:对服务器的请求将无法访问持久层。我们应该模拟连接和存储库。
我已经更新了代码,但存储库仍然没有被覆盖。也许我需要通过外观提供程序来实现它
你可以在这里使用代码My code
发布于 2019-10-20 00:17:12
您可以使用TypeORM fixtures,它们允许您在开发或测试代码时创建fixture/ fake数据。
npm install typeorm-fixtures-cli --save-dev装置可以在YAML文件中表达。例如:
entity: User
items:
user{1..10}:
username: bob
fullname: Bob
birthDate: 1980-10-10
email: bob@example.org
favoriteNumber: 42该库集成了Faker,以帮助生成假数据,如姓名、电子邮件地址、电话numbers...etc。您还可以在不同的装置之间建立关系。
之后,您可以加载这些fixtures并将其与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将假数据加载到内存数据库中,然后运行测试。
发布于 2019-12-23 22:33:03
在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();
});我可以回答任何问题
https://stackoverflow.com/questions/58344126
复制相似问题