I'm looking for some information that I haven't been able to find online.
I've found this article that helped me write out a basic test with axios.
Basically, it looks like this,
// App.test.js
import axios from 'axios';
import { getLayoutScreen } from '..';
import { layoutScreen } from '../data';
jest.mock('axios');
const getLayoutScreen = async () => {
const { data } = await axios.get('get-layout-screen');
return data;
};
it('returns the correct screen layout', async () => {
axios.get.mockResolvedValue({
data: layoutScreen,
});
const screen = await getLayoutScreen();
console.log('screen', screen);
expect(screen).toEqual(layoutScreen);
});
Here, I am overriding all methods of axios
and setting a custom "data"
property on its get
method.
layoutScreen
looks like this,
const layoutScreen = {
screen: {
sidebarOptions: [
{
name: 'Home',
uri: '/',
},
{
name: 'Settings',
uri: '/settings',
},
],
navbarOptions: [
{
name: 'Search',
uri: '/search',
},
],
},
};
export default layoutScreen;
I'm very new to testing with Jest and I'm trying to understand how this particular test makes any sense.
To me, I feel like this particular test will never fail for the simple reason that I always make response.data
equal to layoutScreen
.
In other words it's like saying,
x is equal to A
set y equal to x
check if y is equal x
or,
const a = 1
const b = a
console.log(b === a)
Am I missing some critical aspect of value here? What is the point of a test like this? the layoutScreen
is an object that is received from a backend server that could easily change in the future and this test doesn't make a call to any backend -- I would never know if the structure or data of layoutScreen
would ever change without manually making a call to the server. Everything is effectively hardcoded here and prone to inaccuracies.
Would it not make more sense to not use mockResolvedValue
and, instead, have a local version of the server running, before running any tests? This way, axios would make a call directly to the backend and the test would fail if the JSON isn't identical to my local copy of layoutScreen
.
question from:
https://stackoverflow.com/questions/65952521/using-mockresolvedvalue-when-testing-an-async-api-call-with-jest