如何使用Mocha和sinon测试Ajax请求?
这里是名为testApp的类中的初始化函数:
testApp.prototype.initialize=function() {
$.get(....);
}
在测试中,如果我说,
sinon.stub($,"get", function(d,e) {});
var test = new testApp();
此行引发错误$,但未定义。
我正在用咕unt声来运行摩卡测验。
我尝试使用$和jQuery。但是我总是得到未定义的变量。
有人可以帮忙吗?
这里是在Node环境中测试过的单元测试解决方案。因此,我使用jsdom
为jQuery
提供了一个模拟窗口。否则,$.ajax
和$.get
方法将为undefined
。
index.js
:
const $ = require("./jquery");
function TestApp() {}
TestApp.prototype.initialize = function() {
$.get("https://github.com/mrdulin");
};
module.exports = TestApp;
jquery.js
:
var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = new JSDOM("").window;
global.document = document;
var $ = require("jquery")(window);
module.exports = $;
index.spec.js
:
const $ = require("./jquery");
const sinon = require("sinon");
const TestApp = require(".");
describe("TestApp", () => {
it("should initialize", () => {
const getStub = sinon.stub($, "get");
const test = new TestApp();
test.initialize();
sinon.assert.calledWith(getStub, "https://github.com/mrdulin");
});
});
单元测试结果覆盖率100%:
TestApp
✓ should initialize
1 passing (38ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
index.spec.js | 100 | 100 | 100 | 100 | |
jquery.js | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/37867917