通过函数解析的存根对象函数

时间:2019-02-28 18:58:26

标签: javascript node.js sinon

我正在尝试使用sinon在该对象中添加save方法

const db = {
  user: {
    findOne: () => Promise.resolve({
      id: '43214321-4321-4321-4321-432143214321',
      save: () => Promise.resolve({ // I WANTED TO STUB THIS METHOD
        id: '43214321-4321-4321-4321-432143214321'
      })
    })
  }
}

通过此

beforeEach(() => {
  sinon.stub(db.user.findOne, 'save').rejects()
})

我收到此错误

 TypeError: Cannot stub non-existent own property save

2 个答案:

答案 0 :(得分:0)

const saveStub = sinon.stub().resolves();`

const findOneObject = {
      save: saveStub
};

sinon.stub(db.user, 'findOne').returns(findOneStub);

如果需要,您可以添加id存根

答案 1 :(得分:0)

findOne每次都被解析为新对象,因此无法对save进行存根而又不存根findOne

const saveStub = sinon.stub().rejects();
sinon.stub(db.user, 'findOne').resolves({
  id: '43214321-4321-4321-4321-432143214321',
  save: saveStub
});