I have react component, for example something like this:
JavaScript
x
14
14
1
const MyComponent = (props) => {
2
const [state, setState] = useState(true);
3
const {data} = useContext(myContext);
4
const location = useLocation();
5
6
//A lot of code here
7
8
const myFunction = () => {
9
return { dataFromContext: data, locationFromUseLocation: location, state: state }
10
}
11
12
return <>A lot of other components here</>
13
}
14
And I’m trying to write test that should looks like this:
JavaScript
1
12
12
1
describe('Component test', () => {
2
it('myFunction test', () => {
3
const wrapper = shallow(<MyComponent/>);
4
const expectedResult = {
5
dataFromContext: 'any data here',
6
locationFromUseLocation: 'any location here',
7
state: false
8
};
9
expect(wrapper.dive().instance().myFunction()).toEqual(expectedResult);
10
})
11
})
12
Can I mock useState
, useContext
and useLocation
from <MyComponent/>
and pass my custom data instead of real data from real component?
Advertisement
Answer
After deeper researching I’ve understood, that in such situation I can’t write test only for function in my component. So, I’ve created unit-test, that tests all my component, not only one function.