如何测试sequelize查询(where)逻辑?

时间:2018-01-24 14:59:55

标签: node.js unit-testing sequelize.js

我试图编写单元测试,测试搜索查询是否正确换句话说,如果用where语句写的逻辑返回预期结果。

 async function search(some_data){
   return Event.findOne({
    where: {
      id: 123435,
      [Op.or]: [
        days: {
            [Op.overlap]: some_data.days,
        },
        [Op.or]: [
          {
            startTime: {
              [Op.gt]: some_data.start1,
            },
            endTime: {
              [Op.lt]:some_data.end1,
            },
          },
          {
            startTime: {
              [Op.lt]: some_data.start2,
              [Op.lt]: some_data.end2,
            },
            endTime: {
              [Op.gt]: some_data.end2,
              [Op.gt]: some_data.start2,
            },
          },
        ],
    ],
  },
})};

我需要测试不同输入的结果。 我不想将此测试转换为集成测试并使用原始数据库,因此我使用了sequelize-mock lib,但这只返回我已定义的结果并且不运行实际查询

1 个答案:

答案 0 :(得分:1)

要测试使用正确的参数调用方法,您需要使用依赖项注入和库来“窥探”findOne方法。在下面的示例中,我使用的是Sinon

// app.js
// Note that "Event" must be used an argument in order to mock it out
async function search(Event, some_data) {
  return Event.findOne({
    where: {
      id: 123435
    }
  })
}

如果您的测试文件:

// your test file
const app = require('./app');
const sinon = require('sinon');
const EventMock = {
  findOne: sinon.spy()
};

describe('search', () => {
  it('should call with the right parameters', () => {
    const some_data = {};
    search(EventMock, some_data);

    assert(EventMock.findOne.calledWith({
      where: {
        id: 123435
      }
    }))
  });
});