AngularJS单元测试工厂与jasmine的sweetAlert
我知道我的问题有点简单,但我无法理解它,也无法解决它:| 这是关于测试工厂函数的,它从调用sweetAlert函数 这是我的工厂:AngularJS单元测试工厂与jasmine的sweetAlert,angularjs,unit-testing,jasmine,angularjs-service,angularjs-factory,Angularjs,Unit Testing,Jasmine,Angularjs Service,Angularjs Factory,我知道我的问题有点简单,但我无法理解它,也无法解决它:| 这是关于测试工厂函数的,它从调用sweetAlert函数 这是我的工厂: .factory('sweetAlertService', [function(){ return { /* Alerts: TEXT - 'content', TYPE - 'success', 'warning', 'error', 'default' */ addAlert: fu
.factory('sweetAlertService', [function(){
return {
/*
Alerts: TEXT - 'content', TYPE - 'success', 'warning', 'error', 'default'
*/
addAlert: function(text) {
sweetAlert('', text, 'success');
},
addNormalAlert: function(text, something) {
window.alert('', text, something);
}
};
}])
这是我的测试:
describe('sweetAlertService factory', function() {
var alertService;
beforeEach(inject(function(sweetAlertService) {
spyOn(sweetAlertService, 'addNormalAlert').and.callThrough();
spyOn(sweetAlertService, 'addAlert').and.callThrough();
alertService = sweetAlertService;
}));
it('it should test the normalAlert function in service', function() {
alertService.addNormalAlert('text');
expect(alertService.addNormalAlert).toHaveBeenCalled();
});
it('it should test the addAlert function in sweetAlert service', function() {
alertService.addAlert('text', 'success');
expect(alertService.addAlert).toHaveBeenCalled();
});
});
这很奇怪,但我不知道为什么函数'addNormalAlert'通过了测试,而带有sweetAlert函数'addAlert'的函数没有通过测试
以前有人有过类似的问题吗?提前感谢您的帮助。我认为您缺少在测试用例运行程序中包含的
sweetAlert
js。您已经使用了callThrough
,它基本上除了在已定义的方法上创建spy之外,还调用了实际函数,因此在代码中它将尝试调用sweetAlert,为此,您需要在测试用例运行程序中包含sweetAlert
库。或者,你也可以简单地使用spyOn(sweetAlertService,'addAlert')
而不是spyOn(sweetAlertService,'addAlert')。和.callThrough()
谢谢!没有“and.callThrough()”这就是工作。但你们也说过我可以在我的测试用例运行程序中包含这个库,我该怎么做呢?我还没有在google中找到任何关于将外部库包含到jasmine的好信息,因为我以前已经尝试过:oIt取决于您如何通过一些测试用例运行程序(如karma)或简单地使用spec.html来执行测试用例。1.如果您正在使用某个测试用例运行程序,那么您可以将该测试用例运行程序的配置文件(如“karma.conf.js”)配置为使用sweetAlert
library 2。或者,如果您使用spec.html运行测试用例,只需使用script
标记在该html中包含对sweetAlert
库的引用即可。如果答案有帮助,也请投票。太好了!非常感谢,我使用了karma,我完全忘记了必须在karma.conf.js中添加它:|好的。太棒了如果这些意见有帮助,请投票表决。