我正在测试一个组件,当单击按钮时,该组件会显示ngrx存储中的一些数据。
单击按钮后,路线参数会更改
<button
class="submit"
[routerLink]="['/page']"
[queryParams]="{
period_start: '01.01.19',
period_end: '01.01.19',
submit_search: '->'
}"
>
</button>
如果参数之一是submit_search,那么我将在init上订阅路由参数的更改并调度存储操作。运行测试时,不会记录任何文本。
ngOnInit() {
this.route.queryParams.subscribe(params => {
console.log('Before params.submit_search');
if (params.submit_search) {
console.log('In params.submit_search');
this.store.dispatch(...);
}
});
}
此测试知道点击后的路由已更改(此测试通过):
it('should set route params to filter params', fakeAsync(() => {
const filterButtonElement = fixture.nativeElement.querySelector('.submit');
filterButtonElement.click();
tick();
expect(location.path()).toEqual(
`'/page?period_start=01.01.19&period_end=01.01.19&submit_search=-%3E'`
);
}));
但是此测试表明“派遣”已被调用0次,因此订阅尚未注册路由更改:
describe('SomeComponent', () => {
let dispatchSpy;
let location: Location;
let router: Router;
let route: ActivatedRoute;
let component: SomeComponent;
let fixture: ComponentFixture<SomeComponent>;
let mockStore: MockStore<State>;
let mockGetData: MemoizedSelector<State, SomeData[]>;
const initialState = {};
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
RouterTestingModule.withRoutes([
{
path: 'page',
component: SomeComponent
}
]),
],
declarations: [SomeComponent],
providers: [
provideMockStore({ initialState }),
{ provide: ActivatedRoute, useValue: { queryParams: from([]) } }
]
}).compileComponents();
router = TestBed.get(Router);
route = TestBed.get(ActivatedRoute);
location = TestBed.get(Location);
}));
beforeEach(() => {
fixture = TestBed.createComponent(SomeComponent);
component = fixture.componentInstance;
mockStore = TestBed.get(Store);
mockGetData = mockStore.overrideSelector(SomeSelectors.selectData, []);
router.initialNavigation();
fixture.detectChanges();
});
it('should dispatch store action', fakeAsync(() => {
dispatchSpy = spyOn(mockStore, 'dispatch');
const filterButtonElement = fixture.nativeElement.querySelector('.submit');
filterButtonElement.click();
tick();
expect(dispatchSpy).toHaveBeenCalledTimes(1);
}));
});
为什么未触发订阅?我应该以其他方式提供ActivatedRoute参数吗?
似乎您不得不嘲笑自己ActivatedRoute
想要的东西。
如此更改提供ActivatedRoute
,这有望使您畅通无阻。
import { of } from 'rxjs';
//.....
providers: [....
{
provide: ActivatedRoute,
useValue: { queryParams: of({ submit_search: 'hello', })
}],
现在,要获取一种更改的值的方法queryParams
,您可以执行以下操作:
let dispatchSpy;
let queryParamsValue = new BehaviorSubject({ submit_search: 'hello', });
....
// bind this behavior subject to queryParams in the provider
useValue: { queryParams: queryParamsValue }
然后在测试中,您可以执行以下操作:queryParamsValue.next({ ... });
更改queryParams
are的值并开始订阅。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句