提问人:Vight 提问时间:5/15/2021 更新时间:5/15/2021 访问量:1977
Jest 测试 window.scroll 监听器
Jest testing window.scroll listener
问:
我有一个通过addEventListener附加的窗口滚动事件侦听器。它只是在我到达页面底部时向页面添加额外的电影。 我正在尝试使用笑话来测试它。但是我想不出正确的方法。要么我得到一个测试通过,但处理滚动的函数行没有代码覆盖率。 这是我在 react 中的组件(我删除了经过测试的多余部分):
import React, { useState, useCallback, useEffect } from 'react';
import { useSelector, useDispatch, shallowEqual } from 'react-redux';
import { apiPathUpdated, selectQuery } from '../../modules/query/index';
import {
selectMovies, loadMovies, addMovies, addCurrentMovieTrailerKey,
} from '../../modules/movies/index';
import { loadGenres, selectGenres } from '../../modules/genres/index';
import { updateStatus, selectStatus } from '../../modules/status/index';
import { genreFilterUpdated, selectGenreId } from '../../modules/filters/index';
import SearchResultsPage from './SearchResultsPage';
const SearchResultsPageContainer = () => {
useEffect(() => {
const handleScroll = () => {
if (window.innerHeight + window.pageYOffset === document.body.clientHeight) {
page += 1; //this line stays uncovered
fetchUrl = getFetchUrl(searchQuery, page); //this line stays uncovered
dispatch(addMovies(fetchUrl)); //this line stays uncovered
}
};
window.addEventListener('scroll', handleScroll);
if (page * pageSize >= movies.length && movies.length !== 0) {
window.removeEventListener('scroll', handleScroll);
dispatch(updateStatus('loaded'));
}
return () => window.removeEventListener('scroll', handleScroll);
}, [apiPath, searchQuery, genreId]);
return (
<SearchResultsPage {...bunch of props}/>
);
};
export default SearchResultsPageContainer;
这是我对组件的开玩笑测试(我还删除了额外的测试用例,所以摆脱了一些混乱):
import React from 'react';
import ShallowRenderer from 'react-test-renderer/shallow';
import SearchResultsPageContainer from '../index';
let mockQuerySlice;
let mockGenres;
let mockMovie;
let mockMovies;
let mockMoviesSlice;
let mockFiltersSlice;
let mockStatusSlice;
let mockUseSelector;
let triggerMockUseSelector;
let renderer;
let result;
const map = {};
window.addEventListener = jest.fn((event, cb) => {
map[event] = cb;
});
const spy = jest.spyOn(window, 'addEventListener');
beforeEach(() => {
renderer = new ShallowRenderer();
renderer.render(<SearchResultsPageContainer />);
result = renderer.getRenderOutput();
});
afterEach(() => {
renderer = null;
result = null;
});
describe('render SearchResultsPage component', () => {
it('handles window.scroll event correctly', () => {
map.scroll();
expect(spy).toHaveBeenCalled();
});
});
我尝试使用这个解决方案,但它没有涵盖必要的代码行。(我觉得我错过了什么,但我不知道是什么)
答: 暂无答案
评论
await new Promise((resolve) => setTimeout(resolve, 2000));