Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

reactjs - how do I unit test a React component that inherits state from another component as a prop?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...