![](/img/trans.png)
[英]Testing to see if a function is called with Jest and Typescript, and ts-jest?
[英]Unit Testing in ts-jest with TypeOrm entities
我正在尝试编写测试,但出现错误。 我想我的连接有问题。 “由于尚未建立连接,因此无法对“默认”连接执行操作。”
我有测试文件夹,其中有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");
});
});
我是第一次这样做。 并且坚持了很长时间......有人可以帮我解决这个问题...... :(
试试这个方法,testhelper.ts
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);
await this.dbConnect.initialize()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.