I am trying to write unit tests for code which makes calls to Sequelize to create a database.
I cannot for the life of me figure out how to mock out calls to Sequelize such that I can assert they have created the database tables correctly.
My code which hits Sequelize is as follows:
import { Sequelize, DataTypes } from "sequelize";
export setup_db = async (db_path: string) => {
//Get read/write connection to database
const sequelizeContext = new Sequelize({
dialect: "sqlite",
storage: db_path,
});
//Check if connection is secure, throw error if not
try {
await sequelizeContext.authenticate();
} catch (err) {
throw err;
}
//Define first table
const Table1 = sequelizeContext.define(
"table1",
{
fieldName_1: {
type: DataTypes.STRING
}
},
{ tableName: "table1" }
);
//Define second table
const Table2 = sequelizeContext.define(
"table2",
{
fieldName_1: {
type: DataTypes.STRING
},
{tablename: "table2"}
});
//Define relationship between tables... each Gamertag hasMany wzMatches
Table1.hasMany(Table2);
await Table1.sync();
await Table2.sync();
};
Ideally, I would like to assert that define was called properly, hasMany was called properly, and sync was called for each database.
My test code currently is as follows, although it throws an error about
Cannot spy the authenticate property because it is not a function; undefined given instead.
import { setup_db } from "../../core/dataManager";
const Sequelize = require("sequelize").Sequelize;
describe("DataManager.setup_db", () => {
it("should call sequelize to correctly set up databases", async () => {
//Arrange
const authenticateSpy = jest.spyOn(Sequelize, "authenticate");
//Act
await setup_db("path/to/db.db");
//Assert
expect(authenticateSpy).toHaveBeenCalledTimes(1);
});
});
I'm not sure if spyOn is the right method to call, or whether I can/how I can use jest.mock to mock out and inspect calls to Sequelize.