首页 > 解决方案 > 对 Sequelize Model 的实例进行单元测试

问题描述

我有以下代码:

async save(id: string) {
 const person = await PersonModel.findOne({
  where: { id: id },
 });

 if (!person) {
  await PersonModel.create({
    id: '2345',
    name: 'John Doe',
    age: 25
  });
  return;
 }

 await person.increment({ age: 15 });
}

现在,我想测试 person.increment() ,其中年龄将添加 15。我有以下代码来转义为模型创建新记录的条件。

const findOneFake = sinon.spy(() => {
  return {}; //returns empty object or true
});

const proxy = (proxyquire('./path/to/file.ts', {
  './path/to/PersonModel.ts': {
    default: {
      findOne: findOneFake
    }
  }
})).default;

beforeEach(async () => {
  await save();
});

it('should increment age with 15');

我要怎么做?我该怎么做才能测试它?我可以将 sinon.fake() 用于 PersonModel.create 或 PersonModel.update,但我很难测试 Sequelize 模型的实例。

标签: unit-testingmocha.jssinonchaiproxyquire

解决方案


推荐阅读