1

我没有收到来自测试模块中提供的模拟服务的响应。

我遗漏了什么吗?

我收到错误: TypeError: undefined is not a constructor (evalating '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');
     });
  });
});
4

1 回答 1

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实例中创建 jasmine 间谍

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');
    });
  });
});
于 2018-05-02T13:25:57.690 回答