第一次真正使用sinon,我在模拟库中遇到了一些问题。
我所要做的就是从dao
类中调用一个名为myMethod
的函数。不幸的是,我收到了错误: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
你的问题是你将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>