Open Amber-Williams opened 5 years ago
I have the same problem!
Same problem, the findOne seems to be creating the record if it doesn't exist and returns it, my code:
workerController
const { worker } = require('../../models');
async function getAll() {
const aws = await worker.findAll();
return aws;
}
async function getOne(id) {
const aw = await worker.findById(id);
return aw.get({ plain: true });
}
module.exports = {
getAll,
getOne,
};
spec
const Worker = require('../../app/controllers/workerController');
const { worker } = require('../../models');
jest.mock('../../models/worker', () => () => {
// eslint-disable-next-line global-require
const SequelizeMock = require('sequelize-mock');
const dbMock = new SequelizeMock();
return dbMock.define('worker', {
id: '6037c891-8237-4596-9665-645b2b6a1f4a',
available: true,
createdAt: new Date(),
updatedAt: new Date(),
});
});
describe('Worker Controller Functions', () => {
fit('test', async () => {
const all = await Worker.getAll();
console.log(`BEFORE GET_ONE: ${JSON.stringify(all, null, 2)}`);
const result = await Worker.getOne('1');
console.log(`RESULT: ${JSON.stringify(result, null, 2)}`);
expect(result.id).toEqual('1');
});
});
Results in the following output:
BEFORE GET_ONE: [
{
"id": "6037c891-8237-4596-9665-645b2b6a1f4a",
"available": true,
"createdAt": "2019-09-25T11:30:36.629Z",
"updatedAt": "2019-09-25T11:30:36.629Z"
}
]
RESULT: {
"id": "1",
"available": true,
"createdAt": "2019-09-25T11:30:36.629Z",
"updatedAt": "2019-09-25T11:30:36.629Z"
}
Test Suites: 1 passed, 1 total
Never mind, found this in the code base for findById:
/**
$autoQueryFallback
option on the model should be setfalse
.
Using the following code and I think there's an issue with the findOne() method because it saves over my table variable in my testing with Jest.
const SequelizeMock = require('sequelize-mock'); let dbMock = new SequelizeMock(); let UserMock = dbMock.define('test', { test: 'test', name: 'no' }
describe('Sequelize Model Testing',() => { test('testingggg', async () => { let user = await UserMock.findOne({ where: { name: 'amber' } }) expect(user.name).toBe('amber'); }) })
The expect user.name should be 'no' but its returning as 'amber'.