我们使用Cordova和Ionic框架开发应用程序并使用phonegap-plugin-push。事情进展顺利,但我想用Karma和Jasmine为Push功能编写一些单元测试。
我们有一个工厂PushNotificationService
,其功能为register()
,当用户在应用设置中启用PushNotifications时会调用该工具。目前,我只是想在调用PushNotification.init(...)
时调用register()
进行单元测试。
但是,由于两个原因,这不能按预期工作:
ionic.Platform.isIOS()
返回false,永远不会调用PushNotification.init(...)
。测试失败并显示Expected spy init to have been called.
ReferenceError: Can't find variable: PushNotification
。在我寻找解决方案时,我想知道ionic.Platform
对象和PushNotification对象的定义位置。两者都在根范围内定义(与角度和窗口处于同一级别)。
有人知道在全局(根范围)变量中间谍和模拟函数的可能性吗? 或者你知道我的测试用例的其他解决方案吗?
PushNotificationService
angular.module('myApp')
.factory('PushNotificationService', function () {
function register() {
if (ionic.Platform.isIPad() || ionic.Platform.isIOS() || ionic.Platform.isAndroid()) {
var push = PushNotification.init({
android: {
senderID: "***********",
icon: "icon",
forceShow: true
},
ios: {
alert: "true",
badge: "true",
sound: "true"
},
windows: {}
});
push.on('registration', onRegistration);
push.on('notification', onNotification);
push.on('error', onError);
}
}
测试
describe('PushNotificationService', function () {
beforeEach(module('myApp', function ($provide) {
$provide.value('PushNotification', {
init: jasmine.createSpy('init')
});
// try to mock ionic.Platform.isAndroid(), as PhantomJS is neither Android nor iOS
$provide.value('ionic', {
Platform: {
isAndroid: function () {
return true;
}
}
})
}));
var PushNotificationService;
var PushNotification;
beforeEach(inject(function (_PushNotificationService_, _PushNotification_) {
PushNotificationService = _PushNotificationService_;
PushNotification = _PushNotification_;
}));
it('should call PushNotification.init()', function () {
PushNotificationService.register();
expect(PushNotification.init).toHaveBeenCalled();
});
});