【问题标题】:Sinon stubbing giving 'is not a function' errorSinon 存根给出“不是函数”错误
【发布时间】:2019-02-24 18:06:59
【问题描述】:

第一次真正使用 sinon,我在使用模拟库时遇到了一些问题。

我要做的只是从名为myMethoddao 类中存根/模拟一个函数。不幸的是,我收到了错误:myMethod is not a function,这让我相信我要么将 await/async 关键字放在测试的错误位置,要么我不理解 sinon 100% 的存根。代码如下:

// index.js
async function doWork(sqlDao, task, from, to) {
  ...
  results = await sqlDao.myMethod(from, to);
  ...
}

module.exports = {
  _doWork: doWork,
  TASK_NAME: TASK_NAME
};
// index.test.js

const chai = require("chai");
const expect = chai.expect;
const sinon = require("sinon");

const { _doWork, TASK_NAME } = require("./index.js");
const SqlDao = require("./sqlDao.js");

.
.
.

  it("given access_request task then return valid results", async () => {
    const sqlDao = new SqlDao(1, 2, 3, 4);
    const stub = sinon
      .stub(sqlDao, "myMethod")
      .withArgs(sinon.match.any, sinon.match.any)
      .resolves([{ x: 1 }, { x: 2 }]);

    const result = await _doWork(stub, TASK_NAME, new Date(), new Date());
    console.log(result);
  });

有错误:

  1) doWork
       given task_name task then return valid results:
     TypeError: sqlDao.myMethod is not a function

【问题讨论】:

    标签: javascript node.js async-await sinon sinon-chai


    【解决方案1】:

    您的问题是您将stub 传递给_doWork 而不是传递sqlDao

    存根不是您刚刚存根的对象。它仍然是一个 sinon 对象,用于定义存根方法的行为。完成测试后,您可以使用 stub 恢复存根对象。

    const theAnswer = {
        give: () => 42
    };
    
    const stub = sinon.stub(theAnswer, 'give').returns('forty two');
    
    // stubbed
    console.log(theAnswer.give());
    
    // restored 
    stub.restore();
    console.log(theAnswer.give());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/7.2.4/sinon.min.js"></script>

    【讨论】:

    • 呃,你是对的!谢谢,我想我在尝试将其用作mock 时混淆了电话。如果可以的话,你能否举个例子,因为它是一个模拟而不是一个存根?
    猜你喜欢
    • 2017-06-02
    • 2020-03-29
    • 2020-07-07
    • 1970-01-01
    • 2021-02-27
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    相关资源
    最近更新 更多