创建

时间:2017-07-24 15:12:52

标签: angular unit-testing typescript jasmine

我正在尝试测试以下角度(4.1)服务:

@Injectable()
export class JobService {
  private answerSource = new Subject<AnswerWrapper>();
  answer$ = this.answerSource.asObservable(); 

  answer(answer: AnswerWrapper) {
    this.answerSource.next(answer);
  }

我正在使用此单元测试进行测试:

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [JobService]
    });
  });

  it('should emit $answer on answer()', inject([JobService], (service: JobService) => {
    service.answer$.subscribe(val => expect(val).toEqual('test123'));
    service.answer(('test123' as any))
  }));

然而,我收到错误:

  

无法阅读财产&#39;订阅&#39;未定义的

我真的不明白为什么它会被定义,因为它应该在服务创建上设置?

1 个答案:

答案 0 :(得分:1)

您需要将此行放在构造函数

answer$ = this.answerSource.asObservable(); 

answerSource Subject保证在构造函数运行之前初始化