简体   繁体   中英

How to test axios get request in useEffect using Jest and Enzyme?

I am testing my axios get request using axois-mock-adapter, jest and enzyme. I a 404 error in my console when I run my tests. It started happening once I placed my axios call in useEffect.

Any suggestions on what I might be doing wrong? Thanks in advance

App.js

function App() {
    const [keyword, setKeyword] = useState("")
    const [searchResults, setSearchResults] = useState([])

    useEffect(() => {
        getDataService(keyword)
        .then(({ data }) => {
            setSearchResults(data.suggestions)
        })
        .catch(err => console.log(err))
    }, [keyword])

    return (
        <div className="App">
            <form className="container">
                <InputField keyword={keyword} setKeyword={setKeyword} />
                <SearchResults keyword={keyword} searchResults={searchResults} />
            </form>
        </div>
    );
}

App.test.js

    let mock = new MockAdapter(axios);
    let wrapper;

    describe('App component', () => {
        beforeEach(() => {
         wrapper = mount(<App />)
        });
      it("should get results from api service based on keyword", async () => {
          mock.onGet('search?q=', { params: { keyword: 'shirt'}}).reply(200, {
            data: [{ searchterm: "blue shirt", nrResults: 1000 }]
          });
          axios
            .get("/search?q=", { params: { searchText: "shirt" } })
            .then(response => {
              expect(response).toEqual([{ searchterm: "blue shirt", nrResults: 1000 }]);
              done();
            }).catch((err) => console.log(err))
       })
    })

Error:Error: Request failed with status code 404

If the test passes and you just want to suppress these warnings (I have no idea why these pop up with axios-mock-adapter ), you can do this:

before

const error = console.error;
console.error = jest.fn();

after

console.error = error;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM