I have a React app in which I have some state defined in the App component but which is populated in a child component and I'm having trouble creating a unit test using react-testing-library. Here's the setup:
// App.js
export default function App() {
const [ programs, setPrograms ] = useState([]);
// list of programs to display in ProgramList. Defined in this module so that is available in another module unrelated to ProgramList
return <ProgramList programs={programs} setPrograms={setPrograms} />
}
// ProgramList.js
export default function ProgramList({programs, setPrograms}) {
useEffect( () => loadPrograms(setPrograms), []);
// (this calls a service that uses axios to get the program list and then calls setPrograms to set the value)
return <Select options={generateOptionListFromPrograms(programs)} />}
I'm trying to create a unit test for ProgramList, something like:
// ProgramList.test.js
jest.mock('axios');
test('program list is fetched', async () => {
const mockPrograms = [{name: "program1", label: "Program 1"}, {name: "program2", label: "Program 2"}]
const promise = Promise.resolve({data: mockPrograms});
axios.get.mockImplementationOnce(() => promise);
// something like... but what do i put in for setPrograms?
render(<ProgramList setPrograms={???} programs={???} />);
// I tried putting in
// const[ programs, setPrograms ] = useState([]); // in this function and passing the programs
// and setPrograms to ProgramList but I can't call useState in a test function
});
Or is my whole approach broken and I need to actually have my useEffect in App.js? That would work but it feels wrong - I would rather populate the list closer to where it is being used. I have other similar lists in my app that will need to get populated and I'm not too happy about putting all those useEffects in App.js.
question from:
https://stackoverflow.com/questions/65887791/how-do-i-unit-test-a-react-component-that-inherits-state-from-another-component 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…