gpt4 book ai didi

使用 Mocha.js : How to mock out a callback in mocha? 进行 Javascript 测试

转载 作者:行者123 更新时间:2023-11-30 10:24:09 24 4
gpt4 key购买 nike

我的测试:

describe("Something", function() {
it("does the right thing", function(done) {
callExternalApi(["mockData1", "mockData2"], function(err, ajaxResults) {
// how do I mock out the api requests here and return mocked err, and ajaxResults
});
});
});

我的功能:

function callExternalApi(data, callback) {
$.ajax({
...blah..
success: function(ajaxResults) {
callback(null, ajaxResults);
},
error: function(err) {
callback(err, null);
}
})
}

理想情况下,我不想做某种 http 模拟。我只想不调用此函数并在回调中返回一些内容

最佳答案

你应该看看Sinon .我已经能够在我的 node.js 应用程序中使用它来产生很好的效果。您可以使用它来 stub jQuery 的 ajax 方法,并使 stub 使用如下内容调用您的回调函数:

var stub = sinon.stub(jQuery, "ajax");
stub.yieldsTo("success", [{ foo: "bar" }]);

不要忘记在完成后使用 stub.restore() 恢复 stub 。

看看the docs以获得更高级的用法。

关于使用 Mocha.js : How to mock out a callback in mocha? 进行 Javascript 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20309491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com