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.

Network Error when using nock with axios

See original GitHub issue

When I make real calls, my tests are passing fine; however, when I “nock” my requests, they fail with error message “Network Error.” Here is the full error object I’m catching:

{ Error: Network Error
          at createError (/Users/pauljaworski/Projects/OverEasy/over-easy-ui/node_modules/axios/lib/core/createError.js:15:15)
          at XMLHttpRequest.handleError [as onerror] (/Users/pauljaworski/Projects/OverEasy/over-easy-ui/node_modules/axios/lib/adapters/xhr.js:85:14)
          at XMLHttpRequest.callback.(anonymous function) (/Users/pauljaworski/Projects/OverEasy/over-easy-ui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:251:32)
          at invokeEventListeners (/Users/pauljaworski/Projects/OverEasy/over-easy-ui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:210:27)
          at invokeInlineListeners (/Users/pauljaworski/Projects/OverEasy/over-easy-ui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:168:7)
          at EventTargetImpl._dispatch (/Users/pauljaworski/Projects/OverEasy/over-easy-ui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:126:7)
          at EventTargetImpl.dispatchEvent (/Users/pauljaworski/Projects/OverEasy/over-easy-ui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:91:17)
          at XMLHttpRequest.dispatchEvent (/Users/pauljaworski/Projects/OverEasy/over-easy-ui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:71:35)
          at dispatchError (/Users/pauljaworski/Projects/OverEasy/over-easy-ui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:915:9)
          at Request.client.on.err (/Users/pauljaworski/Projects/OverEasy/over-easy-ui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:623:11)
          at emitOne (events.js:101:20)
          at Request.emit (events.js:188:7)
          at Request.onRequestError (/Users/pauljaworski/Projects/OverEasy/over-easy-ui/node_modules/request/request.js:813:8)
          at emitOne (events.js:96:13)
          at OverriddenClientRequest.emit (events.js:188:7)
          at /Users/pauljaworski/Projects/OverEasy/over-easy-ui/node_modules/nock/lib/request_overrider.js:206:11
          at _combinedTickCallback (internal/process/next_tick.js:67:7)
          at process._tickCallback (internal/process/next_tick.js:98:9)
        config:
         { transformRequest: { '0': [Function: transformRequest] },
           transformResponse: { '0': [Function: transformResponse] },
           headers:
            { Accept: 'application/json, text/plain, */*',
              'Content-Type': 'application/json;charset=utf-8' },
           timeout: 0,
           xsrfCookieName: 'XSRF-TOKEN',
           xsrfHeaderName: 'X-XSRF-TOKEN',
           maxContentLength: -1,
           validateStatus: [Function: validateStatus],
           method: 'post',
           url: '{my url stripped for security}',
           data: '{"petitionerId":"abc123","createdAt":"2016-09-26T16:29:28.612Z","updatedAt":null}' },
        response: undefined }

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:29
  • Comments:22 (4 by maintainers)

github_iconTop GitHub Comments

79reactions
supnatecommented, Jan 15, 2017

I finally resolved the issue by this thread: https://github.com/mzabriskie/axios/issues/305

Below code from @dyakimenko-p works for me:

import {expect} from 'chai'
import axios from 'axios' // v0.15.3
import httpAdapter from 'axios/lib/adapters/http'
import nock from 'nock' // v9.0.2

const host = 'http://localhost';

axios.defaults.host = host;
axios.defaults.adapter = httpAdapter;

describe('suite', () => {
  it('test', done => {
    nock(host)
      .get('/test')
      .reply(200, 'test data');

    axios.get('/test').then(response => {
      expect(response.data).to.be.equal('test data');
      done();
    });
  });
});
22reactions
dragoplutcommented, Nov 23, 2016

My solution by using moxios:

import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as actions from './index'
import * as types from './actionTypes'
import axios from 'axios'
import moxios from 'moxios'

const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);
const API_END_POINT = process.env.REACT_APP_API_ENDPOINT || 'https://web-api.com/api/v1/';

describe('async actions', () => {
  beforeEach(function () {
    moxios.install()
  });

  afterEach(function () {
    moxios.uninstall()
  });

  it('creates returns data in RECV_DATA when axios contacts request has been done', () => {
    moxios.stubRequest(API_END_POINT + 'contacts', {
      status: 200,
      response: { data: { contacts: [{id: 1, firstName: 'FirstName', displayName: 'FirstName'}] }}
    });

    const expectedActions = [
      { type: types.REQ_DATA },
      { type: types.RECV_DATA, data: { contacts: [{id: 1, firstName: 'FirstName', displayName: 'FirstName'}] } }
    ];
    const store = mockStore({ contacts: [] });

    return store.dispatch(actions.getData('contacts'))
      .then(() => {
        expect(store.getActions()).toEqual(expectedActions)
      })
  })
});

Read more comments on GitHub >

github_iconTop Results From Across the Web

Jest returns "Network Error" when doing an authenticated ...
It can be a Jest configuration issue. I solved forcing "node" as jest environment in package.json: "jest": { "testEnvironment": "node" }.
Read more >
Controlling axios HTTP error handling and test it using nock + ...
In this article I have shown how to control of the axios HTTP client library's error emitting mechanism, and how to set up...
Read more >
A brand new website interface for an even better experience!
Network Error when using nock with axios.
Read more >
[Solved]-Network error on posting a request using axios-node.js
The problem is resolved,I was using wrong IP(172.0.0.1) given by hostname --ip-address . Using the inet ip given by ip addr show works....
Read more >
Jest-environment-nock-axios - npm.io
Mock all network requests in tests using nock. Purpose. This environment ensures that no unmocked network requests are made (by calling nock's disableNetConnect) ......
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