ctimmerm / axios-mock-adapter

Axios adapter that allows to easily mock requests
MIT License
3.47k stars 245 forks source link

Feat: Simulate nodejs-level errors ? #365

Open GerkinDev opened 1 year ago

GerkinDev commented 1 year ago

Hi,

For testing purpose, I wanted to check the behavior of my application when receiving errors ECONNRESET, ENOTFOUND, ECONNREFUSED or EHOSTUNREACH, and the only solution I found (after quite some time of research) was to do the following:

axiosMock.onGet('/api/v1/version').reply(() => {
    throw Object.assign(new Error('connect ECONNREFUSED test:1234'), {
        errno: os.constants.errno.ECONNREFUSED,
        syscall: 'connect',
        address: 'test',
        port: 1234,
        code: 'ECONNREFUSED'
    })
});

While it seems to be working as expected, it's rather verbose, and would be super useful to have helpers to throw such errors. I've made a runkit with a few samples of those errors: https://runkit.com/embed/12bax0k5843m

Proposal:

Add an optional parameter to networkError, which would be the code of the error to throw. For what I've seen, errors could look like this:

const NET_ERRORS = {
  ECONNRESET: {
    code: 'ECONNRESET',
    message: 'socket hang up',
    errno: os.constants.errno.ECONNRESET,
  },
  ENOTFOUND: {
    code: 'ENOTFOUND',
    message: 'getaddrinfo ENOTFOUND http://test:1234',
    syscall: 'getaddrinfo',
    hostname: 'http://test',
    errno: os.constants.errno.ENOTFOUND,
  },
  ECONNREFUSED: {
    code: 'ECONNREFUSED',
    message: 'connect ECONNREFUSED 1.2.3.4:1234',
    errno: os.constants.errno.ECONNREFUSED,
    syscall: 'connect',
    address: '1.2.3.4',
    port: 1234,
  },
  EHOSTUNREACH: {
    code: 'EHOSTUNREACH',
    message: 'connect EHOSTUNREACH 1.2.3.4:1234',
    errno: os.constants.errno.EHOSTUNREACH,
    syscall: 'connect',
    address: '1.2.3.4',
    port: 1234,
  },
};

I'm OK to PR

mnikolaus commented 7 months ago

@GerkinDev can you still prepare the PR, this looks like its really needs to be added

GerkinDev commented 7 months ago

I'll do that tomorrow, and publish a built git branch you'll be able to install directly

GerkinDev commented 7 months ago

Done. @mnikolaus you should be able to install it using npm install git+https://github.com/craft-ai/fork-axios-mock-adapter.git#built