index.js 1.3 KB

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