For my User's CRUD, I am writing a UNIT test using sequelize-mock and jest. Model mocking works for me but my issue is regarding the mock model findAll() and findOne() calling both of them in my Users test suite both returns the queued results I defined in my mock model. I'm expecting that if i call findAll(), I should get all the data that are defined in my queued results and if i call findOne() I should only get one data from the queued result based on the id i passed. Setting mock model autoQueryFallback: false doesn't work for me.
Here is a code snippet:
In my controllers/users.js
module.exports = {
async list (req, res) {
Users.findAndCountAll({
limit: 10,
offset: 0
}).then(data => {
console.log('Users >>> ', data);
});
},
async view (req, res) {
Users.findOne({
where: { id: req.params.id }
}).then(data => {
console.log('User Data by ID >>> ', data);
});
}
};
To mock my users model, I have to create a __mocks__ directory adjacent to the models (this is how Jest works). So, I have this directory structure in my models
> models/users.js
> models/__mocks__/users.js
const Users = dbMock.define('users', {}, { autoQueryFallback: false });
Users.$queueResult([
Users.build({
id: 1,
email: 'testActive@test.com',
fullname : 'Test Active Users',
status: 'active',
}),
Users.build({
id: 2,
email: 'testDeleted@test.com',
fullname: 'Test Deleted Users'
status: 'deleted',
}),
]);
Mocks
I want to test both users.list and users.view using the set of data's in my mocked model
jest.mock('../models/users');
describe('Testing use.list()', () => {
it('UsersController.list() should return a status code 201 and all Users data in object array', async () => {
await users.list(req, res);
expect(res.json).toBeCalledWith(
expect.objectContaining({
data: expect.any(Object)
})
);
});
it('UsersController.view() should return a status code 201 and user data obj', async () => {
//Passed req.params.id = 2
await user.login(req, res);
expect(res.status).toHaveBeenCalledWith(failureCode);
expect(res.json).toBeCalledWith(
expect.objectContaining({
data: expect.any(Object)
})
);
});
});