[英]How to implement chained stub in javascript with Jasmine and AngularJs?
I'm not sure if I'm writing the title correct, but here's what I want to do. 我不确定我写的标题是否正确,但这是我想要做的。
I have this code 我有这个代码
var callback = function(result) {
if(result.count < 5) {
msg_id = result.msg_id;
MovieService.getMovies(msg_id, result.count).get(callback, error);
}
if(result.movies.length !== 0) {
setDataToDisplay(result);
}
if(result.count === 5) {
$scope.loading = false;
}
}
MovieService.getMovies(msg_id, 0).get(callback, error);
Basically, when user comes in the first time MovieService will be called and it gets called until the count
equals to 5 times. 基本上,当用户第一次来时,将调用MovieService并将其调用直到count
等于5次为止。 It's like a recursive loop. 这就像一个递归循环。 Now if I want to test this code, I don't know how to do chained stub in Jasmine. 现在,如果我想测试此代码,我不知道如何在Jasmine中进行链式存根。 I could do something similar in Mockito. 我可以在Mockito中做类似的事情。
Here's my test so far. 到目前为止,这是我的测试。
it("should give me the lot of movies", function() {
var movie1 = new MovieBuilder().withTweetId('8').build();
var movie2 = new MovieBuilder().withId('3812').withTweetId('8').build();
var movie3 = new MovieBuilder().withId('3813').withTweetId('8').build();
var movie4 = new MovieBuilder().withId('3814').withTweetId('8').build();
movieService = {
getMovies : function() {
return {
get : function(callback, error) {
callback(
{
'msg_id' : '8',
'count' : '5',
'movies' : [movie1, movie2, movie3, movie4]
});
}
}
}
}
ctrl = controller('MovieTwitterCtrl', {$scope : scope, MovieService : movieService});
expect(scope.movie_groups[0].length).toBe(4);
expect(scope.msg_id).toBe('8');
});
But if I want to test the second, third, fourth and fifth call. 但是,如果我想测试第二,第三,第四和第五次通话。 How do I do that? 我怎么做? Does Jasmine offer something like Mockito? 茉莉花会提供类似Mockito的东西吗? Or how do I do that in pure javascript? 或者我该怎么用纯JavaScript做到这一点?
Thanks a lot. 非常感谢。
You might want to take a look at Sinon , which is a library that provides methods for spys, stubs and mocks and is compatible with Jasmine. 您可能想看一下Sinon ,它是一个提供间谍,存根和模拟的方法并且与Jasmine兼容的库。
In order to automatically invoke your callbacks, you would use stub.yields()
or stub.yieldsTo()
. 为了自动调用您的回调,您可以使用stub.yields()
或stub.yieldsTo()
。 You've also got spy.getCall(n)
that will let you verify the way your method was called during the n
th time. 您还可以使用spy.getCall(n)
来验证第n
次方法的调用方式。 Sinon is written in a way that stubs are also spies... so if you create a stub for your movieService, you'll have access to both yields()
and getCall(n)
. Sinon的编写方式是存根也是间谍...因此,如果您为movieService创建存根,则可以访问yields()
和getCall(n)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.