In my application, I am mocking API calls that come from axios and return data to my application. The objects/arrays that are returned are being modified by the test, but I'm not sure how. The array that gets changed maintains it's new values between two different tests in the same file.
Here is where the mock happens. This function, mockAxiosFetchRequest happens at the beginning of the test and returns different objects depending on the API call. Somehow, the array mockCustomersArray gets modified and retains the new values between tests
import { mockCustomersArray } from './MockData'
const axios = require('axios');
jest.mock('axios');
export const mockAxiosFetchRequest = () => {
axios.mockImplementation((data: any) => {
if (data.url.includes('getCustomers')) {
return {
pageContent: mockCustomersArray
}
} else if (...) {...}
}
}
Here is where the data (the mock response from above) is handled in the application
const invokeGetSegments = (): Promise<any> => {
let segmentList: any = [];
return getSegments()
.then(async response => {
if (response.status === 200) {
segmentList = response.pageContent;
segmentList.unshift(
{ segmentId: 'all-customers', description: 'All Customers' },
); // this is the line where the mock object gets modified
setAllSegments(segmentList);
}
})
.catch(() => {
console.log('error')
});
};
On the line above with unshift, the value also gets shifted onto mockCustomersArray. I'm a little confused how this happens because I wouldn't think that the mock object returned from the jest mock would be in the scope of the invokeGetSegments function.
If I destructure the array like so segmentList = [...response.pageContent] then it works fine and the mock array isn't affected.
When I don't destructure the array and leave it as is in the above code block, I'm not sure how the array that gets returned is changed.