项目作者: WhatAKitty

项目描述 :
fetch mock for react
高级语言: JavaScript
项目地址: git://github.com/WhatAKitty/react-fetch-mock.git
创建时间: 2017-11-05T15:34:12Z
项目社区:https://github.com/WhatAKitty/react-fetch-mock

开源协议:MIT License

下载


react-fetch-mock

Build Status
Known Vulnerabilities

fetch mock for react

React-Native Version

Why FetchMock ?

No fetch mock could be used easily for react.
So, I create one by myself.

Roadmap

  • Combined with Mock.js
  • Support exclude for some other path
  • Proxy for other api server
  • Delay for global and specific path
  • Support RAP system

Usage

Import lib

  1. using npm/yarn
    1. yarn add react-fetch-mock --dev
    2. npm install react-fetch-mock --save-dev

mocks/index.js

  1. export default {
  2. '/api/path': ({ method, url, params, urlparams, headers }) => {
  3. const all = Mock.mock({
  4. 'list|2': [{
  5. 'id|+1': 1,
  6. 'name': '@first @last',
  7. 'age|18-54': 1,
  8. }]
  9. }).list;
  10. return all; // default status is 200
  11. },
  12. '/api/path/{id}': ({ method, url, params, urlparams, headers }) => {
  13. const all = Mock.mock({
  14. 'list|2': [{
  15. 'id|+1': 1,
  16. 'name': '@first @last',
  17. 'age|18-54': 1,
  18. 'urlid': urlparams.id,
  19. }]
  20. }).list;
  21. return all;
  22. },
  23. 'POST /api/path': ({ method, url, params, urlparams, headers }) => {
  24. return {
  25. status: 201,
  26. };
  27. },
  28. 'PUT /api/path/${id}': ({ method, url, params, urlparams, headers }) => {
  29. return {
  30. status: 204,
  31. id: urlparams.id,
  32. };
  33. },
  34. }

index.js

  1. import FetchMock from 'react-fetch-mock';
  2. if (__dev__) {
  3. // attention: mocks file should be under `src/`
  4. window.fetch = new FetchMock(require('path/to/mocks/directory'), {
  5. delay: 200, // 200ms
  6. fetch: window.fetch,
  7. exclude: [
  8. 'http://www.google.com',
  9. '/foo(.*)',
  10. ],
  11. proxy: [{
  12. path: '/path/for/proxy(.*)',
  13. target: 'http://other.proxy.server',
  14. process: (proxied, matches) => {
  15. return `${proxied.target}${matches[1]}`,
  16. },
  17. }],
  18. }).fetch;
  19. }
  20. // if __dev__ is true, it will back the data you defined in mock directory
  21. fetch('/api/path', options);
  22. fetch('/api/path', {
  23. delay: 2000, // /api/path will delayed after 2000ms. Most of suitation, this won't be used usually.
  24. method: 'POST',
  25. headers: {
  26. 'Content-Type': 'application/json',
  27. },
  28. body: JSON.stringify({
  29. name: 'John',
  30. }),
  31. });
  32. fetch('/api/path/123', {
  33. method: 'PUT',
  34. headers: {
  35. 'Content-Type': 'application/json',
  36. },
  37. body: JSON.stringify({
  38. name: 'John2',
  39. }),
  40. });

Example Runing

  1. git clone git@github.com:WhatAKitty/react-fetch-mock.git
  2. cd react-fetch-mock/example/basic
  3. yarn install
  4. yarn start

LICENSE

MIT