我在angular4 app中使用ngrx和sanbox图层方法。 目前我被困在测试sandox.Below是我如何为我的沙箱类编写规范
沙盒代码:
@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));
}
Sandboxs spec.ts
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]: 错误属性:对象({ngTempTokenPath:null,ngTokenPath:[Function]})
我在注入沙盒类时出错了,应用程序沙盒对象未定义
答案 0 :(得分:1)
那是因为你的测试床:
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
}}
]
});
this.MonitoringSandbox = monSandbox;
此行没有任何意义。用这个
替换它sandboxMock: MonitoringSandbox; // place it as the first line of your describe
在每个人之前,做那个
beforeEach(() => {
sandboxMock = TestBed.get(MonitoringSandbox);
})