'Jest test axios error returned from a Promise. I get an "array"
I have this test:
await waitFor(() => {
expect(store.getActions()).toMatchObject([{
type: "TRY_INDEX_ROLES_ITEMS",
},
{
type: "INDEX_ROLES_ITEMS_FAILED",
error: "Error: Request failed with status code 401"
}]);
});
But I get in console:
expect(received).toMatchObject(expected)
- Expected - 1
+ Received + 1
Array [
Object {
"type": "TRY_INDEX_ROLES_ITEMS",
},
Object {
- "error": "Error: Request failed with status code 401",
+ "error": [Error: Request failed with status code 401],
"type": "INDEX_ROLES_ITEMS_FAILED",
},
]
The difference is the "array" notation that really I receive.
In effect this is my action under test:
return this.getApi()
.index(id)
.then(data => {
dispatch({
type: `INDEX_ROLES_ITEMS_SUCCEEDED`,
data
});
})
.catch(error => {
dispatch({
type: `INDEX_ROLES_ITEMS_FAILED`,
error,
});
})
And I get error from:
axiosInstance.interceptors.response.use(
response => {
return response;
},
error => {
return Promise.reject(error);
}
);
I don't want to change error returned with error.toString() (it can works with error.toString(), I just tested it before), I want return from my Axios the error and solve that test.
Thank you
Solution 1:[1]
Since you are using toMatchObject, you can do this.
expect(store.getActions()).toMatchObject([
{
type: 'TRY_INDEX_ROLES_ITEMS',
},
{
type: 'INDEX_ROLES_ITEMS_FAILED',
error: { message: 'Request failed with status code 401' },
},
]);
Or
expect(store.getActions()).toMatchObject([
{
type: 'TRY_INDEX_ROLES_ITEMS',
},
{
type: 'INDEX_ROLES_ITEMS_FAILED',
error: expect.objectContaining({
message: 'Request failed with status code 401',
}),
},
]);
Solution 2:[2]
Not sure if that is what you are asking for, but have you tried just using the error.message?
return Promise.reject(error.message);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | DevMantou |
