我刚刚进入 QUnit 测试,并在我的第一页遇到了问题:S
我们使用 ASP.NET 服务引用来利用 html 页面上的异步数据加载,在同一个项目中创建对 Web 服务的引用。ASP.NET 在幕后所做的(ScriptManager 控件)是创建一个表示服务方法并处理所有 AJAX 调用的 JS 文件。
使用它,我有一个在 document.ready jQuery 事件中调用这些方法之一的页面。我现在正在尝试使用 QUnit 对此 js 文件进行测试,但要避免让 js 文件调用实际的 Web 服务并改用模拟服务。到目前为止,这是我的尝试:
main.js(生产代码文件)
var Service;
$(document).ready(function () {
//class definition created by asp.net behind the scenes
Service = MyProject.services.DataService;
//the method that calls the service
LoadData();
});
function LoadData() {
Service.GetData(OnGetDataSuccess, OnGetDataFailure);
}
main-test.js(测试QUnit代码,本页引用main.js)
function SetupMockService(result) {
Service = { "GetData": function (OnSuccess, OnFailure) {
GetDataCalled = true;
OnSuccess(result);
//this is required in an asyncTest callback, I think?
start();
}, "GetDataCalled": false};
}
$(document).ready(function () {
module("LoadData");
asyncTest("LoadData should call GetData from service", function () {
SetupMockService(result);
LoadData();
equals(Service.GetDataCalled, true, "GetData has been called");
});
此测试失败。LoadData 方法作为原始(main.js)document.ready 事件的一部分被调用,因此它仍然调用生产 Web 服务,并且测试失败,因为从未设置(或在生产中定义)该 GetDataCalled 变量。我做错了 asyncTest 吗?(这是我使用 QUnit 的第一天,所以我很可能是)
我可以看到这个工作的另一种方式是如果我可以覆盖 main.js document.ready 事件,但我不太确定如何做到这一点。我也不想在我的生产 main.js 代码中添加“testEnvironment == true”检查。