我正在尝试编写一些单元测试,但它们都失败了。你能建议我做正确的方法吗?
show(contactId: string, phoneNumber: string, contactType: string, section: string, memberId: string) {
this.$window.onbeforeunload = () => "";
$('.disabledcalldialog').on("click", e => {
this.$window.alert('Please close call dialog and try.');
e.preventDefault();
});

我的spec文件就像
beforeEach(() => {
inject(($rootScope: ng.IScope, $window) => {
spyOn($window, 'onbeforeunload');
$(window).trigger('onbeforeunload');
});
it('should be able to call when changing URL', () => {
expect($window.onbeforeunload).toHaveBeenCalled();

Karma抛出错误消息,如" TypeError:无法获取属性' onbeforeunload'未定义或空引用";
答案 0 :(得分:1)
为您服务:
setUpBeforeunload(): void {
window.addEventListener('beforeunload', this.closeConnection);
}
然后使用Jasmine进行单元测试:
describe('setUpBeforeunload', () => {
it('should set up window eventListener', () => {
spyOn(window, 'addEventListener');
service.setUpBeforeunload();
expect(window.addEventListener).toHaveBeenCalledWith('beforeunload', service.closeConnection);
});
it('should call closeConnection()', () => {
spyOn(service, 'closeConnection');
service.setUpBeforeunload();
window.dispatchEvent(new Event('beforeunload'));
expect(service.closeConnection).toHaveBeenCalled();
});
});
答案 1 :(得分:0)
你试过了吗?
$window.trigger('onbeforeunload');
而不是:
$(window).trigger('onbeforeunload');