如何进行同步测试或不共享存根服务?

时间:2016-10-10 14:55:55

标签: unit-testing testing angular jasmine

我有一些需要服务的测试。我正在使用我注入UserServiceStub的名为SettingsComponent的存根服务,我正在测试它。我在每次测试中重置了UserServiceStub,但是,测试是异步执行的,所以当我重置我的UserServiceStub(这是一个可注入和单例类)时,其他测试已经初始化了它。我的测试很弱,断言错了: - (

我想为每个测试做同步测试或不同的UserServiceStub实例,但我不知道该怎么做......

我试图在UserServiceStub中定义一个名为reset()的方法来重置存根服务,但因为它是异步的,所以它不起作用。另外,我使用afterEach()方法TestBed.resetTestEnvironment()方法执行,但它也不起作用。

我的reset()方法:

reset() {
    this.user = { IBAN: '', SWIFT: '', paypal: '', app_idioma: '' };
  }
  • 我使用的属性称为user,并且已被其他测试覆盖

我的beforeEach()方法就是这个

 let fixture: ComponentFixture<SettingsComponent>;
 let settingsComponent: SettingsComponent;
 beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [SettingsComponent],
      imports: [],
      providers: [
        TranslateService,
        AppService,
        { provide: MockBackend, useClass: MockBackend },
        { provide: HttpToolsService, useValue: HttpToolsServiceStub },
        { provide: BaseRequestOptions, useClass: BaseRequestOptions },
        { provide: UserService, useClass: UserServiceStub } // My stub UserService
      ]
    });

    fixture = TestBed.createComponent(SettingsComponent);
    settingsComponent = fixture.componentInstance;

  });

测试:

 it('#updateSettings should  doesn\'t update the user\'s settings when is wrong', fakeAsync(
    inject([UserService, HttpToolsService, MockBackend],
      (userService: UserServiceStub, httpToolsService: HttpToolsService, mockBackend: MockBackend) => {
        userService.reset(); // It does not work...
        userService.isError = true;
// However, I have reseted my user in UserServiceStub,
// this returns false because settingsComponent.getSettings().IBAN is actually 'XXX' 
// instead of '' (empty) how it has to be
        expect(settingsComponent.getSettings().IBAN).toBe(''); 
      }))
  );

我希望你的答案,如果你有任何问题,请问。

谢谢: - )

1 个答案:

答案 0 :(得分:0)

你尝试过使用getter / setter吗?这样UserServiceStub.user的价值就不会被修改(如果我理解你想要的话)。

class UserServiceStub {
  // instead of:
  // this.user = { IBAN: '', SWIFT: '', paypal: '', app_idioma: '' };
  // use:
  get user() { return { IBAN: '', SWIFT: '', paypal: '', app_idioma: '' }; }
  set user(value) { /* test something here */ }
}