【发布时间】:2022-08-24 06:16:59
【问题描述】:
我正在尝试编写测试,但出现错误。我想我的连接有问题。 \"无法对 \"default\" 连接执行操作,因为连接尚未建立。\"
我有测试文件夹,里面有user.spec.ts 和testhelper.ts
测试助手.ts
// import { Connection, createConnection } from \"typeorm\";
import { DataSource, DataSourceOptions } from \"typeorm\";
import Database from \"better-sqlite3\";
export class TestHelper {
private static _instance: TestHelper;
private constructor() {}
public static get instance(): TestHelper {
if (!this._instance) this._instance = new TestHelper();
return this._instance;
}
private dbConnect!: DataSource;
private testdb!: any;
async setupTestDB() {
this.testdb = new Database(\":memory:\", { verbose: console.log });
this.dbConnect = new DataSource({
name: \"default\",
type: \"better-sqlite3\",
database: \":memory:\",
entities: [\"src/entity/**/*.ts\"],
synchronize: true,
} as DataSourceOptions);
}
teardownTestDB() {
this.dbConnect.destroy();
this.testdb.close();
}
}
用户.spec.ts
import { createUser } from \"../src/controllers/user.controller\";
//@ts-ignore
import { TestHelper } from \"./testhelper\";
beforeAll(async () => {
await TestHelper.instance.setupTestDB();
});
afterAll(() => {
TestHelper.instance.teardownTestDB();
});
describe(\"User Tests\", () => {
test(\"should create user\", async () => {
const body = {
firstname: \"John\",
lastname: \"Brut\",
email: \"john@examle.com\",
password: \"password123\",
};
const res = {};
//@ts-ignore
const user = await createUser(body, res);
//@ts-ignore
expect(user.firstname).toBe(\"John\");
//@ts-ignore
expect(user.lastname).toBe(\"Brut\");
});
});
我是第一次这样做。并且坚持了很长时间......有人可以帮我解决这个问题...... :(
-
我没有看到你在哪里初始化连接。等待 dbConnect.initialize()
-
感谢您的回复。我添加了 await this.dbConnect.initialize();现在我有联系了。在另一件事上需要帮助。测试时出错我认为在 createUser 方法中提供数据的方式错误,它正在等待 req.body 但在这里我在 const body 中提供数据,所以我认为这不是正确的方式去做吧
-
这是我的用户创建方法。我在 user.spec.ts 中做错了什么 const { firstname, lastname, email, password } = req.body;常量用户 = 新用户();用户名 = 名字; user.lastname = 姓氏; user.email = 电子邮件; user.password = 密码; user.avatar = 文件名;等待用户.save();返回 res.json({ 成功: true, user, });
-
您是否只需要测试数据库操作或对 api 的 http 请求?如果 http 请求你也需要模拟它们。
-
是的,我需要 http 请求,因为这个用户创建方法是 http 请求。我只是在想它是在类别数据库测试中……哈哈,我的错
标签: javascript typescript jestjs typeorm