本文介绍了运行npm测试(Angular 2单元测试)后无法读取未定义的属性“ subscribe”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为要测试的组件创建了一个测试(规格)文件。但是,当我运行测试时,它给我一个错误,指出

I've created a testing (spec) file for a component I'm testing. But when I run the test, it gives me an error saying

Cannot read property 'subscribe' of undefined
TypeError: Cannot read property 'subscribe' of undefined
at ComponentUndertest.ngOnInit

中读取未定义
的属性 subscribe我已经在ngOnInit()方法中订阅了某些内容,但是在测试过程中可以忽略订阅吗?还是可以在测试期间伪造订阅?
我在这个问题上搜索了很多,但是找不到与angular2测试有关的任何内容。
预先感谢。

which is obvious because I have subscribed to something in my ngOnInit() method, but can I ignore the subscription during the test? Or can I fake a subscription during testing?I have googled a lot about this issue but couldn't find anything related with angular2 testing.Thanks in advance.

推荐答案

假设您有一个服务,该服务的方法返回一个可观察的值,例如

Assuming you have a service that has a method that returns an observable, say

class SomeService {
  getData(): Observable<Data> {}
}



您可以....



创建一个spy ,在其中返回带有noop订阅功能的对象。

You could....

Create a spy where you return an object with a noop subscribe function.

let mockSomeService = {
  getData: () => {}
}

TestBed.configureTestingModule({
  providers: [
    { provide: SomeService, useValue: mockSomeService }
  ]
})

it('...', () => {
  spyOn(mockSomeService, 'getData').and.returnValue({ subscribe: () => {} })
  // do stuff
  expect(mockSomService.getData).toHaveBeenCalled();
})



您可以...



返回间谍中的实际可观测物

You could...

Return an actual observable in the spy

spyOn(mockSomeService, 'getData').and.returnValue(Observable.of(someData))

也许这比noop subscription方法更可取,因为如果对服务的调用更改了组件中的某些内容,则可能需要这样做测试

Maybe this will be preferred over the noop subscribe method, because if the call on the service is changing something in the component, this is something you probably will want to test

在。这是我平时亲自去的经历。

Do something like in this post. This is personally they was I usually go. It's just a matter of preference.

这篇关于运行npm测试(Angular 2单元测试)后无法读取未定义的属性“ subscribe”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:39