index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const Mock = require('mockjs')
  2. const { param2Obj } = require('./utils')
  3. // for front mock
  4. // please use it cautiously, it will redefine XMLHttpRequest,
  5. // which will cause many of your third-party libraries to be invalidated(like progress event).
  6. function mockXHR(mocks) {
  7. // mock patch
  8. // https://github.com/nuysoft/Mock/issues/300
  9. Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  10. Mock.XHR.prototype.send = function() {
  11. if (this.custom.xhr) {
  12. this.custom.xhr.withCredentials = this.withCredentials || false
  13. if (this.responseType) {
  14. this.custom.xhr.responseType = this.responseType
  15. }
  16. }
  17. this.proxy_send(...arguments)
  18. }
  19. function XHR2ExpressReqWrap(respond) {
  20. return function(options) {
  21. let result = null
  22. if (respond instanceof Function) {
  23. const { body, type, url } = options
  24. // https://expressjs.com/en/4x/api.html#req
  25. result = respond({
  26. method: type,
  27. body: JSON.parse(body),
  28. query: param2Obj(url)
  29. })
  30. } else {
  31. result = respond
  32. }
  33. return Mock.mock(result)
  34. }
  35. }
  36. for (const i of mocks) {
  37. Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  38. }
  39. }
  40. module.exports = mockXHR