我正在测试javascript应用程序,尽管该函数被称为函数总是抱怨它从未被调用过。
这是代码片段和测试
测试规范.js
const Aupdate = require('../accountsUpdate');
it.only('should check if function is called or not', function(done) {
let reqUpdateAccount = {
body: {
Account: 'newAccount1'
}
};
let spy = sinon.spy(Aupdate, 'getUpdateArgs');
Aupdate.accountsUpdate(reqUpdateAccount, res);
expect(spy).to.have.been.called; //test fails
done();
});
文件.js
function getUpdateArgs (Request) {
console.log("func called);
}
function accountsUpdate(req, res) {
let args = getUpdateArgs(req.body);// function spied is called here
...
}
这是解决方案:
index.ts
:
function getUpdateArgs(Request) {
console.log('func called');
}
function accountsUpdate(req, res) {
let args = exports.getUpdateArgs(req.body);
}
exports.getUpdateArgs = getUpdateArgs;
exports.accountsUpdate = accountsUpdate;
index.spec.ts
:
import { expect } from 'chai';
import sinon from 'sinon';
const Aupdate = require('./');
it.only('should check if function is called or not', function() {
let reqUpdateAccount = {
body: {
Account: 'newAccount1'
}
};
const res = {};
let spy = sinon.spy(Aupdate, 'getUpdateArgs');
Aupdate.accountsUpdate(reqUpdateAccount, res);
expect(spy.calledWith({ Account: 'newAccount1' })).to.be.true;
sinon.assert.calledOnce(spy);
});
单元测试结果:
func called
✓ should check if function is called or not
1 passing (7ms)
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57997682