question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unit testing `ECONREFUSED 127.0.0.1:80` with Axios and Mocha

See original GitHub issue

I use MirageJs on a Vue.js application with Axios. It works very well. However, as long as I try to do unit tests, no requests are intercepted by MirageJs. I use Mocha with the @vue/cli-plugin-unit-mocha plugin.

let server: Server<AppRegistry>;
beforeEach(() => {
  server = makeServer({ environment: 'test' });
});

afterEach(() => {
  server.shutdown();
});

it('should handle Axios request', async () => {
  const url = '/fake-url';
  server.get(url, () => new Response(200));

  const { status } = await axios.get(url);

  assert.strictEqual(status, 200);
});

In addition, I get the following error:

Error: Error: connect ECONNREFUSED 127.0.0.1:80
    at Object.dispatchError (node_modules\jsdom\lib\jsdom\living\xhr-utils.js:54:19)
    at Request.<anonymous> (node_modules\jsdom\lib\jsdom\living\xmlhttprequest.js:675:20)
    at Request.emit (events.js:228:7)
    at Request.onRequestError (node_modules\request\request.js:877:8)
    at ClientRequest.emit (events.js:223:5)
    at Socket.socketErrorListener (_http_client.js:415:9)
    at Socket.emit (events.js:223:5)
    at emitErrorNT (internal/streams/destroy.js:92:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
    at processTicksAndRejections (internal/process/task_queues.js:81:21) undefined

Error: Network Error
    at createError (dist\js\webpack:\node_modules\axios\lib\core\createError.js:16:1)
    at XMLHttpRequest.handleError (dist\js\webpack:\node_modules\axios\lib\adapters\xhr.js:83:1)
    at XMLHttpRequest.<anonymous> (node_modules\jsdom\lib\jsdom\living\helpers\create-event-accessor.js:33:32)
    at innerInvokeEventListeners (node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:316:27)
    at invokeEventListeners (node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:267:3)
    at XMLHttpRequestEventTargetImpl._dispatch (node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:214:9)
    at fireAnEvent (node_modules\jsdom\lib\jsdom\living\helpers\events.js:17:36)
    at requestErrorSteps (node_modules\jsdom\lib\jsdom\living\xhr-utils.js:121:3)
    at Object.dispatchError (node_modules\jsdom\lib\jsdom\living\xhr-utils.js:51:3)
    at Request.<anonymous> (node_modules\jsdom\lib\jsdom\living\xmlhttprequest.js:675:20)
    at Request.onRequestError (node_modules\request\request.js:877:8)
    at Socket.socketErrorListener (_http_client.js:415:9)
    at emitErrorNT (internal/streams/destroy.js:92:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
    at processTicksAndRejections (internal/process/task_queues.js:81:21)

I tried to modify the urlPrefix, however the requests are not intercepted and are sent directly to the real server. I also tried to use axios without interceptors or config, without success. On problem #307, the problem was related to an Axios interceptor, which is not my case here.

Do you have any suggestions?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:9 (5 by maintainers)

github_iconTop GitHub Comments

3reactions
samselikoffcommented, Sep 30, 2020

For future travelers: I figured out the issue!

You actually don’t need to run

axios.defaults.adapter = XhrAdapter

At least in my example, when I ran the test Axios defaulted to using the XHR adapter.

Also, the default Vue Test Utils + Vue CLI setup comes with jsdom, so that wasn’t the issue either. There was a window object available, so Mirage (via Pretender) was able to successfully monkey patch window.XMLHttpRequest.

The problem was this line of Axios’ XHR adapter: https://github.com/axios/axios/blob/master/lib/adapters/xhr.js#L28

Since it just calls new XMLHttpRequest(), Axios is using a different XMLHttpRequest object than window’s version, since the node global is not window.

The fix is to force the node global to use window’s version in your tests:

describe("HelloWorld.vue", () => {
  let server;
  let originalXMLHttpRequest = XMLHttpRequest;

  before(() => {
    server = makeServer({ environment: "test" });
    // Force node to use the monkey patched window.XMLHttpRequest
    // This needs to come after `makeServer()` is called.
    // eslint-disable-next-line no-global-assign
    XMLHttpRequest = window.XMLHttpRequest;
  });

  after(() => {
    server.shutdown();
    // Restore node's original window.XMLHttpRequest.
    // eslint-disable-next-line no-global-assign
    XMLHttpRequest = originalXMLHttpRequest;
  });

   it("shows users from the server", (done) => {
    server.create("user", { name: "Sam" });

    const wrapper = shallowMount(HelloWorld);

    setTimeout(() => {
      expect(wrapper.find('[data-test-id="user-1"]').text()).to.eq("Sam");
      done();
    }, 50);
  });
});

And with that everything seems to work!

You can find the example here: https://github.com/miragejs/examples/tree/master/vue-axios-test-utils

2reactions
mcoqblin-hiptestcommented, Sep 18, 2020

What you need is a way to have XMLHttpRequest available in your test environment. I am using Jest with jsdom which provides it. However there is a standalone package that emulates XHR. Could be worth a try to set global.XMLHttpRequest or window.XMLHttpRequest using that.

If you manage to have XHR available in your app, all you need to do is to tell Axios to use XHR instead of the default node HTTP module:

import XhrAdapter from 'axios/lib/adapters/xhr'

axios.defaults.adapter = XhrAdapter

Hope this helps!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Jest test passed but get Error: connect ECONNREFUSED ...
So I figured out and the solution is quite easy. I can't explain why though. This req.get('api/v1/users/') should be /api/v1/users - you ...
Read more >
Uncaught Error: ECONNREFUSED: Connection refused #484
So I'm writing some tests using Mocha, chai and supertest. I'm facing a really weird behavior here on a test that should work...
Read more >
Unit testing Node.js applications using Mocha, Chai, and Sinon
In this article, we will look at how to use Mocha for testing, Chai for assertions and Sinon for mocks, spies, and stubs....
Read more >
connect ECONNREFUSED when integration testing a Node.js ...
In an express.js app that I was integration testing using Mocha the tests suddenly started acting weird with complaint such as:.
Read more >
console.error error - connect econnrefused 127.0.0.1:80
AXIOS request: "Error: connect ECONNREFUSED 127.0.0.1:80" ... I am facing an issue where some Jest unit tests for an Angular application will not...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found