是否可以使用 Jest 仅测试组件中的一个功能?
Is it is possible to test only one function from component with Jest?
我有反应组件,例如这样的东西:
const MyComponent = (props) => {
const [state, setState] = useState(true);
const {data} = useContext(myContext);
const location = useLocation();
//A lot of code here
const myFunction = () => {
return { dataFromContext: data, locationFromUseLocation: location, state: state }
}
return <>A lot of other components here</>
}
我正在尝试编写应该如下所示的测试:
describe('Component test', () => {
it('myFunction test', () => {
const wrapper = shallow(<MyComponent/>);
const expectedResult = {
dataFromContext: 'any data here',
locationFromUseLocation: 'any location here',
state: false
};
expect(wrapper.dive().instance().myFunction()).toEqual(expectedResult);
})
})
我可以从 <MyComponent/>
模拟 useState
、useContext
和 useLocation
并传递我的自定义数据而不是来自真实组件的真实数据吗?
经过更深入的研究,我明白了,在这种情况下,我不能只为组件中的功能编写测试。所以,我创建了 unit-test,它测试了我所有的组件,而不仅仅是一个函数。
我有反应组件,例如这样的东西:
const MyComponent = (props) => {
const [state, setState] = useState(true);
const {data} = useContext(myContext);
const location = useLocation();
//A lot of code here
const myFunction = () => {
return { dataFromContext: data, locationFromUseLocation: location, state: state }
}
return <>A lot of other components here</>
}
我正在尝试编写应该如下所示的测试:
describe('Component test', () => {
it('myFunction test', () => {
const wrapper = shallow(<MyComponent/>);
const expectedResult = {
dataFromContext: 'any data here',
locationFromUseLocation: 'any location here',
state: false
};
expect(wrapper.dive().instance().myFunction()).toEqual(expectedResult);
})
})
我可以从 <MyComponent/>
模拟 useState
、useContext
和 useLocation
并传递我的自定义数据而不是来自真实组件的真实数据吗?
经过更深入的研究,我明白了,在这种情况下,我不能只为组件中的功能编写测试。所以,我创建了 unit-test,它测试了我所有的组件,而不仅仅是一个函数。