Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug or Feature: try-catch around axios breaks tests #165

Open
DaveStein opened this issue Sep 20, 2018 · 1 comment
Open

Bug or Feature: try-catch around axios breaks tests #165

DaveStein opened this issue Sep 20, 2018 · 1 comment

Comments

@DaveStein
Copy link

DaveStein commented Sep 20, 2018

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.

@Kenttleton
Copy link

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`);
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants