首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jasmine SpyObj不返回模拟对象

问Jasmine SpyObj不返回模拟对象
EN

Stack Overflow用户
提问于 2018-03-01 18:12:18
回答 1查看 2.2K关注 0票数 3

我正在尝试测试以下服务。

代码语言:javascript
复制
@Injectable()
export class TranslationService {

  language = 'NL';

  constructor(contextService: ContextService) {
    let context = contextService.getContext();
    this.language = context.language;
  }
}

实际测试:

​

代码语言:javascript
复制
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);
  });

});

​

现在,当运行我的测试时,它返回一个错误:

代码语言:javascript
复制
TypeError: Cannot read property 'language' of undefined

这意味着间谍没有返回我被嘲笑的上下文。但我不知道为什么不是。有人知道吗?

我使用了https://angular.io/guide/testing#service-tests

angular 5.2.4

jasmine 2.8.0

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-01 18:18:00

服务构造函数在模拟getContext存根之前被调用。

它应该是:

代码语言:javascript
复制
contextServiceSpy = TestBed.get(ContextService);
contextServiceSpy.getContext.and.returnValue(context);
service = TestBed.get(TranslationService);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49047315

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档