I've been writing unit tests for Sequelize with a Postgres database. For testing, I'm currently using Jest. Right now, I can get this code to work:
test('email field only takes valid emails', () => {
expect.assertions(2);
let user = Users.build({ email: 'notAProperEmail', password: 'abc123' });
return user.validate().catch(err => {
expect(err).toHaveProperty('errors');
expect(err.errors[0].message).toEqual('Validation isEmail on email failed');
});
})
But for some reason this throws the error "SequelizeDatabaseError: relation "Users" does not exist". Also, the expect method also never gets hit because I get the expected assertion error: "Expected one assertion to be called but received zero assertion calls."
describe('Password is encrypted', () => {
beforeAll(() => {
Users.create({
email: '[email protected]',
password: 'testPassword123'
})
});
test('password is not plain text', () => {
expect.assertions(1);
return Users.findOne({where: { email: '[email protected]' }}).then(response => {
expect(2).toEqual(2)
console.log('console log here: ', response);
});
});
My only guess is that because build doesn't actually save to the database, it returns a value in time for Jest to make an assertion. So my intuition is to use promises to handle the async nature (also, I checked the Jest docs). But it still throws this error and it seems like the promises are being returned before Sequelize is done fetching data from my Postgres Database. I'd really appreciate it if someone could shed light on this issue I'm having!