2017-09-19 38 views
0

我有一个包含负载功能和加载函数调用jQuery的的getJSON功能模块如何使用茉莉嘲笑的jQuery的getJSON回调

load(key,callback){ 
    // validate inputs 
    $.getJSON(this.data[key],'',function(d){ 
     switch(key){ 
     // do some stuff with the data based on the key 
     } 
     callback('success'); 
    }); 
} 

茉莉花2.0我怎样才能模拟出调用的getJSON,但供应数据到匿名函数?

+0

退房间谍https://jasmine.github.io/2.0/introduction.html#section-Spies –

回答

1

我推荐使用Jasmine的ajax插件,它可以模拟所有的AJAX调用(getJSON是ajax调用)。下面是如何做到这一点的例子:

//initialise the ajax mock before each test 
beforeEach(function() { jasmine.Ajax.install(); }); 
//remove the mock after each test, in case other tests need real ajax 
afterEach(function() { jasmine.Ajax.uninstall(); }); 

describe("my loader", function() { 
    it("loads a thing", function() { 
     var spyCallback = jasmine.createSpy(); 
     doTheLoad("some-key", spyCallback); //your actual function 

     //get the request object that just got sent 
     var mostRecentRequest = jasmine.Ajax.requests.mostRecent(); 

     //check it went to the right place 
     expect(mostRecentRequest.url).toEqual("http://some.server.domain/path"); 

     //fake a "success" response 
     mostRecentRequest.respondWith({ 
     status: 200, 
     responseText: JSON.stringify(JSON_MOCK_RESPONSE_OBJECT); 
     }); 

     //now our fake callback function should get called: 
     expect(spyCallback).toHaveBeenCalledWith("success"); 

    }); 
}); 

还有其他的方法,但是这一个已经工作对我很好。更多的文档在这里:

https://github.com/jasmine/jasmine-ajax

+0

这让我没有定义getJasmineRequireObj错误。 – Wanderer

+0

您需要将jasmine ajax插件作为帮助程序添加到您的测试框架中 - 请查看我提供的链接以获取更多详细信息。 –

+0

叫我厚......我不确定这是什么意思......我已经通过npm安装了它。我需要('jasmine-core');'和'require('jasmine-ajax')'。我已经尝试过'var jasmine = Object.assign({},require('jasmine-core'),require('jasmine-ajax'));''''''''''我试过从node_modules复制mock-ajax.js文件到spec/helpers/ – Wanderer