我如何测试我的组件,使用jest和酶与浅和一个React组件,使用useContext挂钩。
如何模拟“pValue.state.fullLang”?
src\Language Select.tsx
import React, { useContext } from 'react';
import { LanguageContext } from './utils/LanguageHook';
function LanguageSelect() {
const pValue: any = useContext(LanguageContext);
return (
<div className="LanguageSelect" data-test="languageSelect-box">
<div className="languageArea">{pValue.state.fullLang}</div>
</div>
);
}
export default LanguageSelect;
src\LanguageSelect.test.tsx
import React from 'react';
import { shallow } from 'enzyme';
import LanguageSelect from './LanguageSelect';
test.only('that the LanguageSelect component exists', () => {
jest.mock('react', () => {
const ActualReact = require.requireActual('react');
return {
...ActualReact,
useContext: () => ({ state: { fullLang: 'mocked context' } }),
};
});
const wrapper = shallow(<LanguageSelect />)
expect(wrapper.find('[data-test="languageSelect-box"]').exists()).toBeTruthy()
wrapper.unmount();
})
2条答案
按热度按时间o4hqfura1#
如果你是在隔离状态下测试这个组件,那么你可以像这样模拟
useContext
:icomxhvb2#
测试包含本地函数但不涉及元素和事件的React函数组件,可以使用Vitest和Enzyme