如何存根返回一个类的类?

时间:2018-07-11 17:25:51

标签: javascript node.js unit-testing sinon

我有一种方法正在进行单元测试,并且正在尝试同时测试

    ...
    let db = new MockDb()
    ...
    db.query(query)
        .then(cursor => {
          return cursor.next()
            .then(result => {
              if (result !== undefined || !data.id) { <-- WANT TO STUB CURSOR.NEXT() SO I CAN TEST RESULT BEING DIFFERENT VALUES
                data.id = uuidv4()
              }
    ...

我有一个用于模拟/存根的文件,其中包含2个类,但只公开其中一个

class MockDb {  
  query (aql) {
    return new Promise((resolve, reject) => {
      return resolve(new MockCursor())
    })
  }
}


class MockCursor {
  next () {
    return new Promise((resolve, reject) => {
      return resolve({foo: 'bar'})
    })
  }
}

module.exports = MockDb

在这种情况下,如何存根cursor.next()返回的内容?

不起作用-给出错误TypeError: cursor.stub is not a function

before(() => {
  let cursor = sinon.stub()
  cursor.stub('next').return(undefined)
  sinon.stub(db, 'query').resolves(cursor)
})

如果我公开MockCursor类,我可以简单地做到这一点:

let db = new MockDb()
let cursor = new MockCursor()
sinon.stub(cursor, 'next').resolves(undefined)
sinon.stub(db, 'query').resolves(cursor)

但是我只是在尝试这样做而不必显式公开MockCursor类

1 个答案:

答案 0 :(得分:0)

这应该有效:

const cursor = sinon
  .stub()
  .returns({
    next: () => Promise.resolve(undefined)
  });
sinon.stub(db, 'query').resolves(cursor);