Jasmine SpyObj 没有 return 模拟对象
Jasmine SpyObj doesn't return mocked object
我正在尝试测试以下服务。
@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);
});
});
现在 运行 我的测试 return 出现错误:
TypeError: Cannot read property 'language' of undefined
这意味着间谍没有 return 我的模拟上下文。但我不知道为什么不是。有人吗?
我用了https://angular.io/guide/testing#service-tests
angular 5.2.4
茉莉花 2.8.0
在模拟 getContext
存根之前调用服务构造函数。
应该是:
contextServiceSpy = TestBed.get(ContextService);
contextServiceSpy.getContext.and.returnValue(context);
service = TestBed.get(TranslationService);
我正在尝试测试以下服务。
@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);
});
});
现在 运行 我的测试 return 出现错误:
TypeError: Cannot read property 'language' of undefined
这意味着间谍没有 return 我的模拟上下文。但我不知道为什么不是。有人吗?
我用了https://angular.io/guide/testing#service-tests
angular 5.2.4
茉莉花 2.8.0
在模拟 getContext
存根之前调用服务构造函数。
应该是:
contextServiceSpy = TestBed.get(ContextService);
contextServiceSpy.getContext.and.returnValue(context);
service = TestBed.get(TranslationService);