已经7天了,我试着阅读了所有的博客,但似乎没有任何效果。
问题
我需要嘲笑useSelector和useDispatch的反应FC。
组件:
/* renders the list of the apis */
const ApiSection = ({ categories }) => {
const [page, setPage] = useState(0);
const [query, setQuery] = useState('');
const [search, setSearch] = useState(false);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchAllApis({ page, category: categories, query }));
}, [page, categories, dispatch, search]);
// all these three are showing as undefined when consoled for UNIT TESTS !!!!!!!
const { apiList, error, loading } = useSelector((state) => {
return state.marketplaceApiState;
});
const renderApiCards = () => {
let apis = Object.values(apiList);
return apis.map((each) => (
<ApiCard key={each.apiId} info={each} data-test="ApiCard" />
));
};
return (
<div className="ApiSection" data-test="ApiSection">
<div className="ApiSection__search">
<div className="ApiSection__cards">{renderApiCards()}</div>
<button onClick={() => setPage(page - 1)}>Previous</button>
<button onClick={() => setPage(page + 1)}>Next</button>
</div>
);
};
export default ApiSection;测试:
const initialState = {
marketplaceApiState: {
apiList: {
a123: { name: 'name', description: 'desc', categories: 'cat', apiId: 'a123'},
},
},
};
const mockDispatch = jest.fn();
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: () => initialState,
useDispatch: () => mockDispatch,
}));
const setup = () => {
const store = createTestStore(initialState);
// I have also tried mount with Provider
return shallow(<ApiListSection categories={['a']} store={store} />);
};
describe('ApiListSection Component', () => {
afterEach(() => {
jest.clearAllMocks();
});
test('Calls action on mount', () => {
setup();
expect(useSelector).toHaveBeenCalled();
expect(mockDispatch).toHaveBeenCalled();
});
});错误:
这是我正在犯的错误:
let apis = Object.values(apiList);
我真的很感激,被困了这么多天
发布于 2021-02-25 11:41:49
理想情况下,你不应该嘲笑钩子,而应该嘲笑商店。
你应该用这样的东西来嘲笑你的商店
据我所知,酶不支持钩子,您需要使用@测试-库/反应对使用钩子的组件进行良好的测试。
import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import thunk from 'redux-thunk';
import { homeReducer } from "../ducks/home";
import { jobReducer } from '../ducks/job';
import { toastReducer } from '../ducks/toast';
const composeEnhancers = compose;
const rootReducer = combineReducers({
home: homeReducer,
toast: toastReducer,
job: jobReducer,
});
const enhancer = composeEnhancers(applyMiddleware(thunk));
export function createTestStore() {
return createStore(rootReducer, enhancer);
}您可以参考我的POC回购这里。
我在那里用过一些很有名的工具。所有这些都列在回购的readme.md中。
https://stackoverflow.com/questions/66367665
复制相似问题