我正在通过 Supertest
向我的开发服务器发出请求来进行集成测试。但是我在如何将数据放入数据库方面遇到了麻烦。例如,在运行 GET 测试之前,我想向数据库中插入数据。但我什至无法从 TypeORM 获得连接:
ConnectionNotFoundError: Connection "default" was not found.
如果我什至从 TypeORM 获得连接,我如何在事务中包装测试并在完成测试后回滚事务以确保集成测试不会影响真实数据库。
基本上,有没有类似 Rails 的 factory_bot
的包?
describe("Templates", (): void => {
describe("GET /api/v1/templates/{templateHash}", (): void => {
let template: Template;
beforeEach(
async (): Promise<void> => {
let templateService: TemplateService = new TemplateService();
let connection: Connection = getConnection("default");
template = new Template(Buffer.from(faker.random.words()), faker.random.uuid(), faker.system.fileName());
await templateService.create(connection, template);
},
);
it("should return a template", (done): void => {
request(config.devEnvEndpoint)
.get(`api/v1/templates/${template.templateHash}`)
.set("Accept", "application/json")
.expect(200)
.end((err, response): void => {
console.log(response);
done();
});
});
});
});
最佳答案
看起来 typeorm 没有获取您的配置。我建议使用 ormconfig.json文件并有两个数据库配置 - 一个用于开发,一个用于测试。
通过拥有两个数据库,您无需担心事务并且可以在测试之间删除数据库。我想交易会更快,但这实际上取决于您的用例(我注意到在进行大量 connection.synchronize()
调用时测试要慢得多)。
然后您可以使用环境变量来确定要实例化哪个连接:
// db.ts
import { Connection, createConnection } from 'typeorm'
let connection: Connection | null = null
export async function getConnection() {
if (connection) {
return connection;
}
// DATABASE_CONFIG can be 'development' or 'test'
// and should correspond to the connection names
// in the ormconfig.json file
connection = await createConnection(process.env.DATABASE_CONFIG);
return connection;
}
export async function closeConnection() {
await connection?.close();
}
然后你可以设置环境变量并运行你的测试:
// DATABASE_CONFIG=test yarn test
import { getConnection, closeConnection } from './db'
let connection: Connection;
beforeAll(async () => {
connection = await getConnection();
});
beforeEach(async () => {
// Drop everything and recreate db
await connection.synchronize(true);
});
afterAll(async () => {
await closeConnection();
});
it('should create a connection', () => {
expect(connection).toBeDefined();
})
关于node.js - 使用 TypeORM 进行集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58479654/