network-helper.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const fs = require('fs')
  2. /**
  3. * Test sandbox environment used to fake network responses.
  4. */
  5. class NetworkSandbox {
  6. constructor (protocol) {
  7. this.protocol = protocol
  8. this._resetFns = []
  9. }
  10. /**
  11. * Reset the sandbox.
  12. */
  13. async reset () {
  14. for (const resetFn of this._resetFns) {
  15. await resetFn()
  16. }
  17. this._resetFns = []
  18. }
  19. /**
  20. * Will serve the content of file at `filePath` to network requests towards
  21. * `protocolName` scheme.
  22. *
  23. * Example: `sandbox.serveFileFromProtocol('foo', 'index.html')` will serve the content
  24. * of 'index.html' to `foo://page` requests.
  25. *
  26. * @param {string} protocolName
  27. * @param {string} filePath
  28. */
  29. serveFileFromProtocol (protocolName, filePath) {
  30. return new Promise((resolve, reject) => {
  31. this.protocol.registerBufferProtocol(protocolName, (request, callback) => {
  32. // Disabled due to false positive in StandardJS
  33. // eslint-disable-next-line standard/no-callback-literal
  34. callback({
  35. mimeType: 'text/html',
  36. data: fs.readFileSync(filePath)
  37. })
  38. }, (error) => {
  39. if (error != null) {
  40. reject(error)
  41. } else {
  42. this._resetFns.push(() => this.unregisterProtocol(protocolName))
  43. resolve()
  44. }
  45. })
  46. })
  47. }
  48. unregisterProtocol (protocolName) {
  49. return new Promise((resolve, reject) => {
  50. this.protocol.unregisterProtocol(protocolName, (error) => {
  51. if (error != null) {
  52. reject(error)
  53. } else {
  54. resolve()
  55. }
  56. })
  57. })
  58. }
  59. }
  60. /**
  61. * Will create a NetworkSandbox that uses
  62. * `protocol` as `Electron.Protocol`.
  63. *
  64. * @param {Electron.Protocol} protocol
  65. */
  66. function createNetworkSandbox (protocol) {
  67. return new NetworkSandbox(protocol)
  68. }
  69. exports.createNetworkSandbox = createNetworkSandbox