jest.unmock("./DB"); jest.unmock("./util/insert"); jest.unmock("./util/ColumnDataType"); jest.mock("./util/columns", () => { return { default: () => jest.fn().mockImplementation((schemaName: string, tableName: string) => { if (schemaName === "schema" && tableName === "table1") { return { id: { type: "int" }, name: { type: "longtext" }, field1: { type: "string", isNullable: true }, json1: { type: "json", isNullable: true }, }; } throw new Error("Unknoww table"); }), }; }); import mockMysql = require("./../__mocks__/mysql"); import DB from "./DB"; const connection = { query: jest.fn(), }; mockMysql.createConnection.mockReturnValueOnce(connection); connection.query.mockImplementation((_, __, cb: any) => { cb(null, "query1"); }); const db = new DB({ user: "root", password: "123", }); beforeEach(() => { connection.query.mockClear(); }); it("create", () => { expect(db.connection).toBe(connection); }); it("insert", async () => { const res = await db.insert("schema.table1", [{ id: 1, name: "test1" }]); expect(res).toBe("query1"); expect(connection.query.mock.calls).toEqual([[ "insert into table1(`id`,`name`) values ?", [[[1, "test1"]]], jasmine.any(Function), ]]); }); it("insert on duplicate key update", async () => { await db.insert("schema.table1", [{ id: 1, name: "test1" }], { onDuplicateKeyUpdateAll: true }); expect(connection.query.mock.calls).toEqual([[ "insert into table1(`id`,`name`) values ? on duplicate key update `id` = VALUES(`id`), `name` = VALUES(`name`)", [[[1, "test1"]]], jasmine.any(Function), ]]); }); it("insert with excesses fields", async () => { await db.insert("schema.table1", [ { id: 1, name: "test1", e1: true, field1: "str1" }, { name: { test: "x" }, id: 2, ee2: "v", json1: { temp: 8 } }, ]); expect(connection.query.mock.calls[0][0]).toBe("insert into table1(`id`,`name`,`field1`,`json1`) values ?"); expect(connection.query.mock.calls[0][1][0]).toEqual([ [1, "test1", "str1", null], [2, "{\"test\":\"x\"}", null, "{\"temp\":8}"]]); });