如何修复角度单元测试期间未定义的“无法读取属性订阅”?

时间:2019-01-03 06:31:53

标签: angular karma-jasmine

Angular6-单元测试错误“无法读取未定义的属性'subscribe'”

我正在为具有多个相关性的角度分量编写单元测试。这些依赖服务之一具有一些可观察的属性。我尝试模拟此服务,但在标题中抛出错误,

spec.ts

describe('Component', () => {
let mockService= jasmine.createSpyObj(['property1', 'property2', 'property3']);

beforeEach(async(() => {
    TestBed.configureTestingModule({
declarations: [testComponent],
providers: [
......someOther,
{ provide service, useValue: mockService},
......someOther
]
}).compileComponents();

fixture = TestBed.createComponent(testComponent);
component = fixture.componentInstance;
}));

it('should be created', () => {
expect(component).toBeTruthy();
  });
});

ts文件具有

this.Service.property1.subscribe(() => {})
this.Service.property2.subscribe(() => {})
this.Service.property3.subscribe(() => {})

期望测试用例通过,但失败,并出现标题中的错误

1 个答案:

答案 0 :(得分:0)

与其以这种方式创建间谍,不如尝试在

中创建间谍。
  

然后

  

compileComponents

let service:Service

.compileComponents().then(()=>{

  spyOn(service:Service, 'any method / property').and.returnValue(Observable.of(MOCKDATA));

)}

我希望对您有帮助