无法从提供的模拟服务获得响应

时间:2018-05-02 13:04:30

标签: angular jasmine angular-test

我未能收到测试模块中提供的模拟服务的回复。

我是否省略了什么?

我收到错误: TypeError:undefined不是构造函数(评估'service.getUser.subscribe')*

class MockUserService {
  getUser: jasmine.createSpy('getUser').and.returnValue(Observable.of({'name': 'user1'})),
  getUser2: jasmine.createSpy('getUser2').and.returnValue(new BehaviorSubject({'name': 'user2'}))   
}

fdescribe('should use mocked services', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;
  let service;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [.....],
      providers: [{provide: UserService, useClass: MockUserService}],
      declarations: [TestComponent],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();

    service = TestBed.get(UserService);
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
  });

  it(`should provide mocked service`, () => {
     service.getUser.subscribe(user => {
       console.log(`user: ${user}`);
       expect(user.name).toBe('user1');
     });

    service.getUser2.subscribe(user => {
       console.log(`user: ${user}`);
       expect(user.name).toBe('user2');
     });
  });
});

1 个答案:

答案 0 :(得分:0)

我认为问题的根源在于您使用:设置这些属性,=试图设置属性的类型而不是值。您应该使用class MockUserService { getUser = jasmine.createSpy('getUser').and.returnValue(Observable.of({'name': 'user1'})), getUser2 = jasmine.createSpy('getUser2').and.returnValue(new BehaviorSubject({'name': 'user2'})) } 将属性设置为等于创建的间谍:

MockUserService

您不需要创建UserService课程。您可以在describe('should use mocked services', () => { ... beforeEach(async(() => { TestBed.configureTestingModule({ ... providers: [UserService], ... }) .compileComponents(); })); ... it(`should provide mocked service`, () => { spyOn(service, 'getUser').and.returnValue(Observable.of({'name': 'user1'})); spyOn(service, 'getUser2').and.returnValue(new BehaviorSubject({'name': 'user2'})); service.getUser.subscribe(user => { console.log(`user: ${user}`); expect(user.name).toBe('user1'); }); service.getUser2.subscribe(user => { console.log(`user: ${user}`); expect(user.name).toBe('user2'); }); }); }); 实例

之外创建茉莉花间谍
mouseup