如何在 jasmine 中测试沙箱类

潘卡伊

我在 angular4 应用程序中使用 ngrx 和 sanbox 层方法。目前我被困在测试沙箱。下面是我如何为我的沙箱类编写规范

沙盒代码:

 @Injectable()
 export class MonitoringSandbox {
 constructor(public deviceService: DeviceService,
    public appStateManagerService: AppStateManagerService) {
  }

 public getDeviceIdWithRowIndex(): Observable<Array<RowIdDeviceIdKeyValue>> {
    return 
    this.appStateManagerService.getFromStore<Array<RowIdDeviceIdKeyValue>>(
        state => state.devicesState.kvRows
    );
}

public setSelectedDevice(deviceId: string) {
    this.appStateManagerService.saveToStore(new SetSelectedDevice(deviceId));
}

沙盒规范

 describe('Monitoring Sandbox', () => {
 beforeEach(
 async(() => {
  TestBed.configureTestingModule({
    imports: [UnitTestsModule]
  });
 })
);
beforeEach(inject([MonitoringSandbox], (monSandbox: MonitoringSandbox) => {
  this.MonitoringSandbox = monSandbox;
})
);
/* teh failing test */
it('Should get and set selected row  value from session storage for selected 
 row', () => {
let selectedRow: string;
this.MonitoringSandbox.setSelectedRow('143');
selectedRow = this.MonitoringSandbox.getSelectedRow();
expect(selectedRow).toEqual('143');
});

我收到以下错误:

Chrome 68.0.3419 (Windows 7 0.0.0) 监控沙箱应从会话存储中获取和设置选定行的选定行值 FAILED

错误:StaticInjectorError[MonitoringSandbox]:错误属性:Object({ ngTempTokenPath: null, ngTokenPath: [ Function ] })

我在注入沙箱类时哪里出错了,沙箱对象未定义

用户4676340

那是因为你的测试平台:

  TestBed.configureTestingModule({
    imports: [UnitTestsModule]
  });

没有与您的 Sandbox 相关的依赖项。

此外,我不知道在这种情况下沙箱是什么,也许您可​​以提供一些代码来帮助您理解并为您提供适合此问题的解决方案?

编辑

您的沙箱是一项服务(用 装饰@Injectable),因此您需要将其导入到您的测试台中。

由于您不测试沙箱,而是测试您的组件,因此您需要模拟它。

这看起来像这样:

  TestBed.configureTestingModule({
    imports: [UnitTestsModule],
    providers: [
      { provide: MonitoringSandbox, useValue: {
        getDeviceIdWithRowIndex: () => Observable.of(/* an array of RowIdDeviceIdKeyValue */),
        setSelectedDevice: () => null // does nothing, so no return needed
      }}
    ]
  });

编辑 2

this.MonitoringSandbox = monSandbox;

这条线没有任何意义。用这个替换它

sandboxMock: MonitoringSandbox; // place it as the first line of your describe

在你的每一个之前,做到这一点

beforeEach(() => {
  sandboxMock = TestBed.get(MonitoringSandbox);
})

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章