我在Angular6中测试服务时遇到问题。该服务实现了我从'ngx-webstorage-service'库获得的SessionStorage。当用户单击另一个选项卡时,我使用它来保留选定的产品。不幸的是,它不起作用。第一个测试不起作用(应该创建服务)。我应该如何模拟服务并添加InjectionToken?
我试图将模拟会话对象声明为StorageService,但是Angular给了我一个错误。这是我在测试中第一次使用该库。
我的构造函数服务如下:
import { Injectable, Inject, InjectionToken } from '@angular/core';
import { StorageService } from 'ngx-webstorage-service';
const STORAGE_KEY = 'productId';
export const MY_PRODUCTS_SERVICE_STORAGE =
new InjectionToken<StorageService>('MY_PRODUCTS_SERVICE_STORAGE');
@Injectable({
providedIn: 'root'
})
export class ProductService {
productIds: number[] = [];
constructor(@Inject(MY_PRODUCT_SERVICE_STORAGE) private storage: StorageService) {
const ids: number[] = this.storage.get(STORAGE_KEY);
if (typeof ids !== 'undefined') {
this.productIds= ids;
}
}
}
我的测试规范文件:
import { TestBed, inject } from '@angular/core/testing';
import { ProductService, MY_PRODUCT_SERVICE_STORAGE } from './product.service';
import { StorageService, SESSION_STORAGE } from 'ngx-webstorage-service';
describe('ProductService ', () => {
let service: ProductService;
const mockSession = {
get: () => '',
set: () => null,
has: () => true,
remove: () => null,
clear: () => null,
withDefaultTranscoder: () => null
} as StorageService;
beforeEach(() =>
service = TestBed.get(ProductService));
TestBed.configureTestingModule({
providers: [
ProductService,
{ provide: MY_PRODUCTS_SERVICE_STORAGE, useExisting: SESSION_STORAGE }
]
});
it('should be created', inject([mockSession], () => {
expect(service).toBeTruthy();
}));
});
预期的输出将创建服务,但是不幸的是,我从角度测试中得到了错误: 错误:StaticInjectorError(DynamicTestModule)[InjectionToken MY_PRODUCTS_SERVICE_STORAGE]: StaticInjectorError(平台:核心)[InjectionToken MY_PRODUCTS_SERVICE_STORAGE]: NullInjectorError:InjectionToken没有提供者MY_PRODUCTS_SERVICE_STORAGE!
答案 0 :(得分:0)
我已替换:
get: () => ''
收件人:
get: () => []
和:
useExisting: SESSION_STORAGE
收件人:
useValue: mockSession
和:
it('should be created', inject([mockSession], () => {
expect(service).toBeTruthy();
}));
收件人:
it('should be created', () => {
expect(service).toBeTruthy();
});
它终于可以工作了。