2016-09-24 48 views
1

我得到了一个角服务模样

function userService() { 
    // A library provide methods that not used $http service and not $.ajax either 
    this.lib = theLib; 

    // This one will invoke "api/v1/user" 
    this.getAllUser = function() { 
    return lib.getAll(); 
    } 
} 

如何测试以下

it('should return all user', function() { 
    // How can I mock the returned data without using $http 
    userService.getAllUser(); 
}) 

这些功能它可能是库测试服务如果它使用$ http或$ ajax,那么我很容易使用$httpBackend或模拟ajax的返回。还有另一种方法来模拟theLib,但里面有很多方法,但我不认为这是个好主意。这种情况下的任何建议?

+0

你可以尝试使用[XHR-模拟(https://github.com/jameslnewell/xhr-mock) – jcubic

+0

谢谢@jcubic。我会尝试。 – tmhao2005

+0

这真的取决于你正在瞄准的测试水平是什么。如果你对单元测试(即服务本身)感兴趣,那么你应该嘲笑图书馆,而不是通信提供商。 –

回答

0

在Jasmine 2.0中,引入了用于测试ajax的新API。

Here是你可以做一些这样的事情的链接进行

,成立了STIB AJAX每次测试前和每次使用后卸载它,你可以参考上面的链接以获取更多信息

beforeEach(function() { 
    jasmine.Ajax.install(); 
    jasmine.Ajax.stubRequest('YOUR_URL_HERE').andReturn({ 
    responseText: 'YOUR_RAW_STUBBED_DATA_HERE' 
    }); 
}); 

afterEach(function() { 
jasmine.Ajax.uninstall(); 
}); 

it('My Ajax Test', function() { 
// . . . code that makes an ajax request . . . 
}) 

对于XHR请求,你可以尝试这样的事情

beforeEach(function() { 
// spyOn(XMLHttpRequest.prototype, 'open').andCallThrough(); // Jasmine 1.x 
    spyOn(XMLHttpRequest.prototype, 'open').and.callThrough(); // Jasmine 2.x 
    spyOn(XMLHttpRequest.prototype, 'send'); 
}); 

it("should return all user", function() { 
    userService.getAllUser(); 
    expect(XMLHttpRequest.prototype.open).toHaveBeenCalled(); 
    }); 
+0

感谢您的评论。但在这种情况下,lib不使用ajax,所以嘲笑ajax是没有用的。 – tmhao2005

+0

k让我更新我的答案xhr请求然后 – AbhiGoel

相关问题