Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize unit-test mocking with postgres and sequelize-mock

I'm trying to do build unit-test with sequelize-mock, node and postgres, but whenever I query against my mock I'm getting results no matter if I got the current data in my mock or not. It's seems sequelize-mock is automatically generated results based on my query. I tried to use autoQueryFallback option, but I'm getting SequelizeMockEmptyQueryQueueError.

for example:

describe('/GET/:email/exists', () => {
  it('it should check if email exists - it should fail', async () => {
    const email = '[email protected]';
    try {
      const res = await fakeDbUtil.isEmailExistsDb(email);
      chai.assert.equal(res, null);
    } catch(e) {
      console.log(e);
    }
  });
});

I do not have the given email in my mock DB, so I expecting to get null result. However, I'm getting result containing my mock together with the current email (override my mock original email).

I don't sure if I'm doing something wrong? Are there some other good mocking frameworks out there which can work with postgres and sequelize?

like image 635
wizard Avatar asked Dec 27 '17 09:12

wizard


1 Answers

Yes, autoQueryFallback: true option allows sequelize-mock to generate automatic results based on the Model properties. If you don't want the automated results you can declare autoQueryFallback: false when you are defining a model object or on the sequelizeMock object.

    const UserMock = SequelizeMock.define("user", {}, {
                          autoQueryFallback: false
                        });

To mock the data you can use Sequelize-mock QueryInterface to queue the results for a query.

So in your case, you can mock email something like below.

UserMock.$queueResult(UserMock.build({
  id: 2,
  email: "[email protected]"
}));

And then you can call your DB query function and expect the result.

const res = await fakeDbUtil.isEmailExistsDb(email);
expect(res.email).not.toBe("expectedEmail")

For more information about mocking sequelize model check this out.

This test is more of a Jest framework way. It's a nice testing framework. If you want to give it a try, check out this

like image 195
Subbu Avatar answered Sep 20 '22 20:09

Subbu