So in the first file, let's say db.ts - it exports a function, let's call it dbHandler, with content similar to the following:
try {
let db = new sqlite3.Database('./sampleDBName.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err: Error) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the database.');
});
db.serialize(function() {
db.run("CREATE TABLE IF NOT EXISTS sample_table (id VARCHAR, sample_data INTEGER, PRIMARY KEY (id))") // ensure table exists
.run("INSERT OR IGNORE INTO sample_table (id, sample_data) VALUES ($1)", ['1',1]) // ensure row exists
.all("SELECT * FROM sample_table WHERE id = $1", [1], async (error: Error, rows: Array<any>) => {
if(error) {
console.log(error);
}
// logic in here (calls other functions & more based on data in rows)
sampleObjectMock.objectFunc({content: "sample content"});
});
});
db.close((err: Error) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});
} catch(e) {
console.log(e);
}
And in the index.spec.ts (test) file:
describe("sample use case", () => {
it("sample test", async () => {
let sampleObjectMock = {
objectFunc: jest.fn()
}
await dbHandler(sampleObjectMock);
expect.assertions(1);
expect(sampleObjectMock.objectFunc).toHaveBeenCalledWith({content: "sample content"});
}
}
I'm getting errors stating the following for each console log in opening and closing the database:
"Cannot log after tests are done. Did you forget to wait for something async in your test?"
In addition to this, the 'objectFunc()' is never called, it works outside of the jest testing environment - I believe it doesn't work due to the callback functions of the database calls only running after the tests themselves have already run to completion asynchronously. Any ideas?
I have tried adding jest.runAllTimers() or jest.runAllTicks(), but I have little experience with these types of functions and they didn't seem to change anything. Thanks in advance if anyone can help with this.