gpt4 book ai didi

javascript - 在 Jasmine 中测试回调方法的功能

转载 作者:行者123 更新时间:2023-12-02 14:12:51 25 4
gpt4 key购买 nike

我有以下服务。

InvService(...){
this.getROItems = function(cb){
$http.get('url').success(cb);
}
}

使用上述内容的 Controller 之一:

var roItems = [];  
InvService.getROItems(function(res){
roItems = res.lts.items;
});

在 Jasmine 中,我想测试是否为 roItems 分配了响应中的值。我怎样才能实现这个目标?

最佳答案

我建议您对服务和 Controller 进行单独的测试。如果您想测试 roItems 是否已分配,您需要测试您的 Controller 。然后,您可以模拟您的服务,因为它与 Controller 测试无关,并使其返回您想要的任何内容。你需要这样的东西:

describe('my awesome test', function() {

it('my awesome test block',
inject(function(InvService, $controller) {
//This mocks your service with a fake implementation.
//Note that I mocked before the controller initialization.
spyOn(InvService, 'getROItems').and.callFake(function(cb){
var resultFake = {
lts: {
items: "whatever you want"
}
}
cb(resultFake);
});
//This initializes your controller and it will use the mocked
//implementation of your service
var myController = $controller("myControllerName");

//Here we make the assertio
expect(myController.roItems).toBe("whatever you want");
}
)
});

关于javascript - 在 Jasmine 中测试回调方法的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39351766/

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