I have a typescript project with sequelize, and I have two tests that needs to mock the sequelize.authenticate function with different outputs. Here is what I have:
test('Return successful health', async () => {
jest.mock('sequelize', () => {
const mSequelize = {
authenticate: (): Promise<void> =>
new Promise(resolve => {
resolve();
}),
};
const actualSequelize = jest.requireActual('sequelize');
return { Sequelize: jest.fn(() => mSequelize), DataTypes: actualSequelize.DataTypes };
});
const mSequelizeContext = new Sequelize();
const healthCheck = new HealthCheck(mSequelizeContext);
const actualResult = await healthContext.checkHealthStatus();
expect(actualResult).toEqual(true);
});
test('Return failed health on db error', async () => {
jest.mock('sequelize', () => {
const mSequelize = {
authenticate: (): Promise<void> =>
new Promise((_, reject) => {
reject(new Error('mock db error'));
}),
};
const actualSequelize = jest.requireActual('sequelize');
return { Sequelize: jest.fn(() => mSequelize), DataTypes: actualSequelize.DataTypes };
});
const mSequelizeContext = new Sequelize();
const healthContext = new HealthContext(mSequelizeContext);
const actualResult = await healthContext.checkHealthStatus();
expect(actualResult).toEqual(false);
});
afterEach(() => {
jest.resetAllMocks();
});
the Sequelize object is initialized as:
const DBInstance = new Sequelize(config.db.database, config.db.username, config.db.password,
{ host: config.db.host, dialect: config.db.dialect as Dialect, repositoryMode: true, logging: config.db.debug, });
export default DBInstance;
And I just call the function in another place where:
import MySqlInstance from '...';
...
await MysqlInstance.authenticate();
...
As you can see, they have different mocking for authenticate
function. However the above code returns the following error:
Dialect needs to be explicitly supplied as of v4.0.0
Seems the mocking didn't take in effect. I can put one of them on the top level (outside of the describe), which will work but it can only take into effect once, the other mock is not set properly.
How should I provide 2 different mocks to the authenticate function?
sequelize.authenticate()
method? – Arcane