简体   繁体   中英

Mock Ajax (Reactjs + Mobx)

I want to make some fake my ajax calls so when on localhost I can bring back dummy data from a fake method instead of doing real calls to my server(where the structure might not exist).

What is the best way to do this in reactjs + mobx?

I was thinking of making a fake store as this is where all my actions are with my ajax calls but that would involve always making the entire store with all functions.

I then though of maybe extracting out the ajax calls from the store and then mockup those calls but I am not sure the best way to do that.

Use json-server for faking api calls and redux for state management, I have used this in one of my projects. It is quite simple and requires very less boilerplate code. Redux updates a global store through actions and components can subscribe to store for changes.

See documentation here-

https://github.com/typicode/json-server

http://redux.js.org/

Example from my app- You can make a fake store by creating a db.json and then you can use either default routes provided by json-sever or create your own.

This can be your db.json

{
    "questions": [
        {
            "id": 2,
            "question": "A train running at the speed of 60 km/hr crosses a pole in 9 seconds. What is the length of the train?",
            "options": [
                "120 metres",
                "180 metres",
                "324 metres",
                "150 metres"
            ],
            "answer": 4
        },
        {
            "id": 3,
            "question": "The length of the bridge, which a train 130 metres long and travelling at 45 km/hr can cross in 30 seconds, is",
            "options": [
                "200 m",
                "225 m",
                "245 m",
                "250 m"
            ],
            "answer": 3
        }
    ]
}

start this mock api by running this json-server --watch db.json in your folder with db.json file.

Then use http://localhost:3000/questions

Comment if you want more detailed information on any of stuff mentioned above. I can provide you sample code as I have implemented this full flow.

have you tried nock ?

Nock is an HTTP mocking and expectations library for Node.js

Nock can be used to test modules that perform HTTP requests in isolation.

For instance, if a module performs HTTP requests to a CouchDB server or makes HTTP requests to the Amazon API, you can test that module in isolation.

Shouldn't make any difference if you are using it for localhost dev or unit testing. The library should just mock requests and not care for your environment.

The basic idea to do this would be to setup a check that says "If I am in localhost, then mock all my requests". You can mock individual requests or just mock them all in like one function by providing a regex as the hostname or path.

https://github.com/node-nock/nock#specifying-hostname https://github.com/node-nock/nock#specifying-path

The library that @crystalwill provided allows you to do this from my 2 mins of skimming the README.md.

It allows individual request mocking and seems to allow all multiple request mocking, eg you can specify Regex to match all strings for the hostname or path and return a common response for all of them if you wish.

Use a mocking library, don't recreate one. Also it's much better to use this HTTP mocking library than mocking your store. What happens if you need to send a request outside of your store? It will hit your server which defeats the entire purpose.

Another alternative to the already proposed is to implement rapidly a node server that runs locally (in development mode) and that responds with some dummy JSON data for each endpoint.

That way you keep your frontend code clean, regardless the tech stack used, and delegate the implementation details on your server. The only thing required in your frontend (assuming you are using a build tool like webpack or alike to bundle up your JavaScript) is to use environmental variables to use your local or prod server endpoints.

This is typically done using this webpack plugin: https://webpack.js.org/plugins/environment-plugin/

let apiEndpoint;
if (process.env.NODE_ENV === 'production') {
  apiEndpoint = 'https://yourProdServer/api'
} else {
  apiEndpoint = 'https://localhost:8080/api'
}

Then in your npm scripts configure something like:

"dev": "webpack",
"prod": "NODE_ENV=production webpack"

Do you know superagent ?

It's very interesting http client and has a very cool mocker plugin .

It works fine in a nodejs server or in a webbrowser. I use it in a everyday base. Very easy and well documented.

You can write custom callbacks to handle requests to certain urls or urls patterns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM