javascript - sinon spy 检查是否调用了 func 总是返回 false 虽然函数
问题描述
我正在测试 javascript 应用程序,尽管该函数被称为函数总是抱怨它从未被调用。
这是代码片段和测试
test.spec.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
推荐阅读
- sql - 比较 datetimeoffset 和 timezone SQL
- ios - 本地化字符串的 RelativeDateTimeFormatter 上下文
- multilingual - 多语种 Ghost 具有相同的蛞蝓
- android - 使用 ajax 发布到 IP 在 Cordova 中不起作用,但在手机浏览器中可以正常工作
- java - 我在 Excel 表中的单元格迭代器和空白单元格类型方面面临问题。如何动态处理空白单元格和空白列调整
- android - 如何在 NodeJS+Android 中处理 Google 登录
- java - 私有的、受保护的访问修饰符和抽象之间的区别
- java - 可以使用什么方法来获得该地区的准确日期和时间?
- java - 尝试使用 MouseListener 和 MouseMotionListener 创建圈子——我做错了什么?
- python - ImageDataGenerator 不喜欢我的 fashionMNIST 数据集。它需要哪个输入?