Mocha Sinon测试ajax请求(在Node中)

问题描述 投票:1回答:1

如何使用Mocha和sinon测试Ajax请求?

这里是名为testApp的类中的初始化函数:

 testApp.prototype.initialize=function() {
  $.get(....);
}

在测试中,如果我说,

sinon.stub($,"get", function(d,e) {});
var test = new testApp();

此行引发错误$,但未定义。

我正在用咕unt声来运行摩卡测验。

我尝试使用$和jQuery。但是我总是得到未定义的变量。

有人可以帮忙吗?

javascript node.js mocha sinon chai
1个回答
0
投票

这里是在Node环境中测试过的单元测试解决方案。因此,我使用jsdomjQuery提供了一个模拟窗口。否则,$.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

© www.soinside.com 2019 - 2024. All rights reserved.