[英]Sinon stubbing giving 'is not a function' error
first time really using sinon and I am having some issues with the mocking library. 第一次真正使用sinon,而模拟库出现了一些问题。
All I am trying to do is stub/mock out a function from a dao
class called myMethod
. 我要做的就是从一个名为myMethod
的dao
类中存根/模拟一个函数。 Unfortunatly, I am getting the error: myMethod is not a function
, which makes me believe I am either putting the await/async
keywords in the wrong spots of the test or I don't understand sinon stubbing 100%. 不幸的是,我遇到了错误: myMethod is not a function
,这使我相信我将await/async
关键字放在测试的错误位置,或者我不理解sinon 100%存根。 Here is the code: 这是代码:
// 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);
});
With error: 有错误:
1) doWork
given task_name task then return valid results:
TypeError: sqlDao.myMethod is not a function
Your issue is that you're passing stub
to _doWork
instead of passing sqlDao
. 您的问题是您将stub
传递到_doWork
而不是传递sqlDao
。
A stub isn't the object that you just stubbed. 存根不是您刚刚存根的对象。 It is still a sinon object that you use to define the behaviour of the stubbed method. 它仍然是一个sinon对象,可用于定义存根方法的行为。 When you're done with your tests, you use stub
to restore stubbed object. 完成测试后,可以使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.