Scenario
I have the following type of function that I wish to test. This function has
File to be tested
export const doSomething = () => {
sequelize.transaction(async t => {
customModel.upsert(dataObject, { transaction : t })
otherCustomModel.upsert(otherDataObject, { transaction : t })
})
}
Here customModel
and otherCustomModel
are valid models written using sequelize.define
in their respective files.
Here sequelize
is the following thing
import Sequelize from 'sequelize';
const connectionParams = {
// assume valid config is present
}
const sequelize = new Sequelize(connectionParams);
(async () => {
try {
await sequelize.authenticate();
console.log('Sequelize authenticated successfully');
} catch (error) {
console.log(`Unable to connect to the database: ${error}`);
}
})();
export default sequelize;
Requirements
I wish to write a testcase with the following checks:
-
Test that the following functions are called once.
transaction
customModel.upsert
otherCustomModel.upsert
-
The entire function executes
How can I go ahead and mock a sequelize transaction using jest for such functions?
My Test
test("text", () => {
// mocks
sequelize.transaction = jest.fn()
customModel.upsert = jest.fn()
otherCustomModel.upsert = jest.fn()
doSomething()
// assertions
expect(sequelize.transaction).toBeCalled();
expect(customModel.upsert).toBeCalled();
expect(otherCustomModel.upsert).toBeCalled();
})
Error Faced
expect(jest.fn()).toBeCalled()
Expected number of calls: >= 1
Received number of calls: 0
62 | expect(sequelize.transaction).toBeCalled();
Versions
S No. | Dependency | Version |
---|---|---|
1 | sequelize | ^6.19.1 |
2 | jest | ^27.5.1 |
P.S. : Any other suggestions to enhance my test case are welcomed!
2
Answers
You should be able to do it e.g. like this:
And in you test case:
and after that you can do your assertions e.g.:
I would write it something like this