【发布时间】:2018-03-01 18:17:59
【问题描述】:
我正在尝试测试以下服务。
@Injectable()
export class TranslationService {
language = 'NL';
constructor(contextService: ContextService) {
let context = contextService.getContext();
this.language = context.language;
}
}
实际测试:
describe('TranslationService', () => {
let service: TranslationService;
let contextServiceSpy: jasmine.SpyObj<ContextService>;
beforeEach(() => {
const contextSpy = jasmine.createSpyObj('ContextService', ['getContext']);
TestBed.configureTestingModule({
providers: [
TranslationService,
{provide: ContextService, useValue: contextSpy}]
});
service = TestBed.get(TranslationService);
contextServiceSpy = TestBed.get(ContextService);
});
it('should create an instance', () => {
const context: Context = {
language: 'EN'
};
contextServiceSpy.getContext.and.returnValue(context);
expect(service).toBeDefined();
expect(contextServiceSpy.getContext.calls.count()).toBe(1, 'spy method was called once');
expect(contextServiceSpy.getContext.calls.mostRecent().returnValue).toBe(context);
});
});
现在运行我的测试时,它返回错误:
TypeError: Cannot read property 'language' of undefined
这意味着 spy 没有返回我的模拟上下文。但我不知道为什么它不是。有人吗?
我用https://angular.io/guide/testing#service-tests
角度 5.2.4
茉莉花2.8.0
【问题讨论】:
标签: javascript angular jasmine2.0