axios-mock-adapter
axios-mock-adapter copied to clipboard
Bug or Feature: try-catch around axios breaks tests
I found a way to have expectations fail, but not bubble to fail the test. If I do something like this in my test, the failed expectation will be caught by the code further below.
From my test file:
mock.onGet('http://www.test.com/mypath').reply(config => {
expect(true).toEqual(false);
return [200, []];
});
From my actual file:
try {
const validParams = {}; // real stuff in code
return axios(validParams);
}
catch (e) {
// If third party fails, doing a graceful return instead of throwing
myFunctionThatLogs();
return [];
}
Basically my code is catching the error that moxios is throwing and everything runs as normal. Not honestly sure there is a way around this, but wanted to call it out if there's some best practice I'm missing.
I was seeing the same thing. This seems to be a weird scope issue in try-catch blocks. Some investigation should go into this but to mitigate this use the chaining technique for promise resolution. This is what I did in Typescript but should work for Javascript implementations as well.
public post = async <T, B>(url: string, headers: Record<string, string>, body?: B | undefined): Promise<T> => {
const data = axios
.post<T>(url, this.buildOptions(headers, body))
.then((res) => {
if (res.status !== 200) {
logger.error(`Received ${res.status} status when hitting ${url}`);
throw Error('Error interacting with integration layer');
}
return res.data as T;
})
.catch((err) => {
logger.error(`Error when hitting ${url} with ${err.code}`, err.message, err.stack);
throw Error(`${err.code} error interacting with integration layer: ${err.message} ${err.stack}`);
});
return data;
};
with tests
test('post', async () => {
mock.onPost(`/test`).reply(200, `Healthy`);
const result = await axiosAbstraction.post(`/test`, {});
expect(result).toBe(`Healthy`);
});