gpt4 book ai didi

angular - 如何测试具有去抖时间的效果?

转载 作者:行者123 更新时间:2023-12-04 02:56:09 26 4
gpt4 key购买 nike

我正在使用 NgRx 并想测试我的效果。有些效果确实有去抖时间。像这个例子:

@Effect() searchImage$ = this.actions$.pipe(
ofType(来自ImageLibraryActions.SEARCH_IMAGES),
map (( Action :fromImageLibraryActions.SearchImages)=> action.query),
去抖时间(300),
switchMap(query: string) => this.imageLibraryService.getImagesBySearching(query)),
map((images: LibraryImage[]) => new fromImageLibraryActions.LoadImages(images)));

如何正确测试它们。我尝试了以下方法:

describe('SearchImages$', () => {
it('should return loadImages action', fakeAsync(() => {
const action = new fromImageLibraryActions.SearchImages('test');
const images = [
{ uploaderId: 1 } as LibraryImage,
{ uploaderId: 2 } as LibraryImage
];

const loadImagesAction = new fromImageLibraryActions.LoadImages(images);

actions$ = hot('--a-', { a: action });

tick(300);
getTestScheduler().flush();

const expected = cold('--b-', { b: loadImagesAction });
expect(effects.searchImage$).toBeObservable(expected);
}));
});

最佳答案

我喜欢使用假计时器,只是跳过时间,更多详细信息请参阅我的博客 https://timdeschryver.dev/blog/testing-an-ngrx-project#effect-tests-and-fake-timers .

afterEach(() => {
// don't forget to reset the timers
jest.useRealTimers();
});

it('fetch$ dispatches success action with fake timers', () => {
jest.useFakeTimers();

const actions = new ActionsSubject();
const effects = new WerknemersEffects(actions, getMockStore(), newWerknemerService());

const result: Action[] = [];
effects.fetch$.subscribe((action) => {
result.push(action);
});

const action = werknemerActions.missingWerknemerOpened({ werknemerId: 3 });
actions.next(action);

jest.advanceTimersByTime(10_000);

// 🔦 to make tests less brittle, wait for the task to finish with `runOnlyPendingTimers` or `runOnlyPendingTimers` instead of advancing the time with `advanceTimersByTime`.
// This makes sure that the test isn't impacted when the duration is modified.
jest.runOnlyPendingTimers();

expect(result).toEqual([
werknemerActions.fetchWerknemerSuccess({
werknemer: newWerknemer({ id: action.werknemerId }),
}),
]);
});

关于angular - 如何测试具有去抖时间的效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53060208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com