我面临着为服务编写单元测试的问题,该服务在构造函数中有一些动作。它阻止了我的测试,我不确定如何处理它:(
这是服务类别:
import { Injectable } from '@angular/core';
import { Storage } from '@dvs-angular/storage';
const COOKIE_STORAGE_KEY = 'cookiePanelDisplayed';
@Injectable()
export class CookiePanelService {
public panelVisible: boolean = true;
constructor(
private storage: Storage
) {
this.panelVisible = !this.storage.has(COOKIE_STORAGE_KEY);
}
public close(): void {
this.panelVisible = false;
if (this.storage.has(COOKIE_STORAGE_KEY)) {
return;
}
this.storage.set(COOKIE_STORAGE_KEY, true);
}
}
这就是我的测试样子
import { TestBed, inject } from '@angular/core/testing';
import { CookiePanelService } from './cookie-panel.service';
import { Storage } from '@dvs-angular/storage';
const storageMock = {
has: jasmine.createSpy()
};
const COOKIE_STORAGE_KEY = 'cookiePanelDisplayed';
describe('Service: CookiePanelService', () => {
let cookiePanelService: CookiePanelService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
CookiePanelService,
{
provide: Storage,
useValue: storageMock
},
]
});
});
beforeEach(
inject([CookiePanelService], (service: CookiePanelService) => {
cookiePanelService = service;
})
);
it('should set panelVisible to false on close', () => {
cookiePanelService.panelVisible = true;
cookiePanelService.close();
expect(cookiePanelService.panelVisible).toBe(false);
});
});
我在控制台中得到的是:
TypeError: this.storage.has is not a function
请您建议如何处理构造函数以及如何避免这种情况。
答案 0 :(得分:1)
按如下所示创建您的模拟。
const storageMock = {
has: function() {},
set: function() {},
};
保持简单。 useValue
刚好是对象。
jasmine.createSpy()
返回一个spy
。而has
应该是function
更新:
您可以为以下功能设置spy
。
spyOn(storage, 'has');
expect(storage.set).toHaveBeenCalledWith(COMPANY_STORAGE_KEY_MOCK);
答案 1 :(得分:0)
最简单的解决方案之一是在您的计算机上添加
@option
前缀 组件所在构造函数中的服务实例 注入这项服务。
like:-
import {Optional} from "@angular/core";
constructor( @Optional() private cookiePanelService:CookiePanelService ){}
我希望这行得通