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.

I think I am likely confused but wanted to ask here to get some clarification. Should Mirage be able to work with other HTTP libraries such as axios?

I made a small test case using Jest + Create-React-App and Mirage doesn’t seem to be intercepting the request:

// mirage.test.ts
import axios from "axios";
import { Server, Response } from "miragejs";

let server: any;
beforeEach(() => {
  server = new Server({
    routes() {
      this.namespace = "api";

      this.post("/resource", () => {
        return new Response(200, {}, "Success");
      });
    }
  });
});

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

it("can post a resource", async () => {
  await axios.post("/api/resource", JSON.stringify({ data: 1 }));
});

npm run test -- mirage.test.ts

 FAIL  mirage.test.ts
  ✕ can post a resource (73ms)

  ● can post a resource

    connect ECONNREFUSED 127.0.0.1:80



Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.172s, estimated 1s
Ran all test suites matching /mirage.test.ts/i.

However, if I switch to using fetch, the test passes:

it("can post a resource", async () => {
  await fetch("/api/resource", {
    method: "POST",
    body: JSON.stringify({ data: 1 })
  });
});

npm run test -- mirage.test.ts

 PASS  mirage.test.ts
  ✓ can post a resource (471ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.738s, estimated 2s
Ran all test suites matching /mirage.test.ts/i.

Active Filters: filename /mirage.test.ts/
 › Press c to clear filters.

Watch Usage
 › Press a to run all tests.
 › Press f to run only failed tests.
 › Press o to only run tests related to changed files.
 › Press q to quit watch mode.
 › Press p to filter by a filename regex pattern.
 › Press t to filter by a test name regex pattern.
 › Press Enter to trigger a test run.
  console.groupCollapsed node_modules/miragejs/dist/mirage-cjs.js:5946
      Mirage: [200] POST http://localhost:80/api/resource

  console.groupCollapsed node_modules/miragejs/dist/mirage-cjs.js:5965
        Response

  console.log node_modules/miragejs/dist/mirage-cjs.js:5966
        Success

  console.groupCollapsed node_modules/miragejs/dist/mirage-cjs.js:5968
        Request (data)

  console.log node_modules/miragejs/dist/mirage-cjs.js:5969
        { data: 1 }

  console.groupCollapsed node_modules/miragejs/dist/mirage-cjs.js:5971
        Request (raw)

  console.log node_modules/miragejs/dist/mirage-cjs.js:5972
        FakeRequest {
      _eventListeners: 
       { loadend: [ [Function] ],
         abort: [ [Function] ],
         load: [ [Function] ],
         progress: [ [Function] ],
         loadstart: [ [Function] ] },
      readyState: 4,
      requestHeaders: { 'content-type': 'text/plain;charset=UTF-8' },
      requestBody: '{"data":1}',
      status: 200,
      statusText: 'OK',
      upload: 
       { _eventListeners: 
          { loadend: [Array],
            abort: [Array],
            load: [Array],
            progress: [Array],
            loadstart: [Array] } },
      onload: [Function],
      onerror: [Function],
      ontimeout: [Function],
      onabort: [Function],
      method: 'POST',
      url: 'http://localhost:80/api/resource',
      async: true,
      username: undefined,
      password: undefined,
      responseText: 'Success',
      response: 'Success',
      responseXML: null,
      responseURL: 'http://localhost:80/api/resource',
      sendFlag: true,
      sendArguments: { '0': '{"data":1}' },
      errorFlag: false,
      params: {},
      queryParams: {},
      responseHeaders: { 'Content-Type': 'application/json' } }

Any advice or direction would be appreciated. The app I was trying to integrate Mirage into is quite large and uses axios pretty much everywhere. I can also post a repo that reproduces this if needed.

Thanks.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:11 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
janeivindcommented, Aug 4, 2020

@samselikoff Just startet implementing miragejs, great stuff! Using axios and miragejs with my vue app, my code is working fine via browser, but i get a ECONNREFUSED 127.0.0.1:80 in my tests. The server setup file is imported to the tests, and I have console logged that the instance is set up i routes().

To isolate the problem, I ended up with a single test to bypass my setup.

import { Server, Model } from 'miragejs'
import axios from 'axios';
....
    it.only("routes config option works", async () => {
        server = new Server({
            environment: "test",
            models: {
                user: Model
            },
            routes() {
                this.namespace = "api";

                this.get("/users");
            }
        });
        server.createList("user", 3);
        let data = await axios.get("/api/users").then(res => res.json());
        expect(data).toEqual({
            users: [{ id: "1" }, { id: "2" }, { id: "3" }]
        });
        server.shutdown()
    });

Now, i still get get the ECONNREFUSED 127.0.0.1:80 error… Any suggestions?

1reaction
mcmillhj-wtacommented, Feb 4, 2020

@samselikoff Weird, the repo I was using to attempt to re-create this is passing … It must be something unique to my setup that is unrelated to MirageJS. I am going to close for now while I investigate.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Getting Started | Axios Docs
Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs...
Read more >
How to make HTTP requests with Axios
Why use Axios? ... The most common way for frontend programs to communicate with servers is through the HTTP protocol. You are probably...
Read more >
Axios tutorial - GET/POST requests in JavaScript with Axios
Axios is a promise based HTTP client for the browser and Node.js. Axios makes it easy to send asynchronous HTTP requests to REST...
Read more >
Making HTTP requests with Axios
Axios is a promise-based HTTP library that lets developers make requests to either their own or a third-party server to fetch data.
Read more >
axios/axios: Promise based HTTP client for the browser ...
Promise based HTTP client for the browser and node.js - GitHub - axios/axios: Promise based HTTP client for the browser and node.js.
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