How to test a function which call get API and output a response. I tried but I am able to test initial data which is in state , but I want to know how to test the function which updates the initial state when the API is called .
code Example what I have Tried. CodeSandboxLink : [testing code]1
Context API
Here I have called the function userDataFunc which is in context and initial data is stored in state userData
import React, { Component, createContext } from "react";
import axios from "axios";
export const globalC = createContext();
export class Gprov extends Component {
state = {
userData: []
};
componentDidMount() {}
userDataFunc = async () => {
await axios(`https://jsonplaceholder.typicode.com/users`)
.then((res) => {
if (res.status === 200) {
this.setState({
userData: res.data
});
}
})
.catch((err) =>
this.setState({
userDataerror: err
})
);
};
render() {
return (
<globalC.Provider
value={{
...this.state,
userDataFunc: this.userDataFunc
}}
>
{this.props.children}
</globalC.Provider>
);
}
}
context Test File
Here I have performed some test such as initial state value which passes the test cases but i not able to test the function can anyone help me out .
import React from "react";
import { Gprov } from "./context";
import { create } from "react-test-renderer";
import { waitForElement, cleanup } from "@testing-library/react";
import axiosMock from "axios";
afterEach(cleanup)
describe("Context Page", async () => {
const component = create(<Gprov />);
const instance = component.getInstance();
it("it updates dose correctly", () => {
console.log("instance", instance);
expect(instance.state.userData).toStrictEqual([]);
});
it("fetches data and display", async () => {});
});