I'm building a React Native app and I'm writing my unit tests using Jest.
(As you can see from this question,) I'm writing a function that checks if there is a network connection.
Here is the function (checkNetwork.ts
):
import { NetInfo } from "react-native";
import { NO_NETWORK_CONNECTION } from "../../../../config/constants/errors";
const checkNetwork = (): Promise<boolean | string> =>
new Promise((resolve, reject) => {
NetInfo.isConnected
.fetch()
.then(isConnected => (isConnected ? resolve(true) : reject(NO_NETWORK_CONNECTION)))
.catch(() => reject(NO_NETWORK_CONNECTION));
});
export default checkNetwork;
Now I want to mock this function when testing another function that makes API calls.
I created a folder called __mocks__
adjacent to checkNetwork.ts
inside checkNetwork/
(see folder structure below). In it I created another file called checkNetwork.ts
, too, which contains the mock and looks like this:
const checkNetwork = () => new Promise(resolve => resolve(true));
export default checkNetwork;
The function that uses this function makes a simple fetch request (postRequests.ts
):
import checkNetwork from "../../core/checkNetwork/checkNetwork";
export const postRequestWithoutHeader = (fullUrlRoute: string, body: object) =>
checkNetwork().then(() =>
fetch(fullUrlRoute, {
method: "POST",
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" }
}).then(response =>
response.json().then(json => {
if (!response.ok) {
return Promise.reject(json);
}
return json;
})
)
);
The folder structure looks like this:
myreactnativeproject
├── app/
│ ├── services/
│ │ ├── utils/
│ │ │ └── core/
│ │ │ └── checkNetwork/
│ │ │ └── checkNetwork.ts
│ │ ├── serverRequests/
│ │ │ └── POST/
│ │ │ └── postRequests.ts
│ . .
│ . .
│ . .
.
.
.
I then created another file called postRequests.test.ts
within POST/
to write unit tests for postRequests.test.ts
. I would now expect for Jest to automatically use the mock which returns true. But what is actually happening is that the test fails returning NO_NETWORK_CONNECTION
. How can I get Jest to use the mock?