app-test-setup.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. const path = require('path')
  5. const http = require('http')
  6. const currentDirName = __dirname
  7. const mockFixtureDir = path.resolve(currentDirName, '../fixtures')
  8. module.exports.fixtureDir = mockFixtureDir
  9. module.exports.initJest = (mockFixture) => {
  10. jest.setTimeout(1200000)
  11. const mockAppDir = path.join(mockFixtureDir, mockFixture)
  12. process.env.__TAURI_TEST_APP_DIR = mockAppDir
  13. }
  14. module.exports.startServer = (onSuccess) => {
  15. const responses = {
  16. writeFile: null,
  17. readFile: null,
  18. writeFileWithDir: null,
  19. readFileWithDir: null,
  20. readDir: null,
  21. readDirWithDir: null,
  22. copyFile: null,
  23. copyFileWithDir: null,
  24. createDir: null,
  25. createDirWithDir: null,
  26. removeDir: null,
  27. removeDirWithDir: null,
  28. renameFile: null,
  29. renameFileWithDir: null,
  30. removeFile: null,
  31. renameFileWithDir: null,
  32. listen: null
  33. }
  34. function addResponse(response) {
  35. responses[response.cmd] = true
  36. if (!Object.values(responses).some((c) => c === null)) {
  37. server.close(onSuccess)
  38. }
  39. }
  40. const app = http.createServer((req, res) => {
  41. // Set CORS headers
  42. res.setHeader('Access-Control-Allow-Origin', '*')
  43. res.setHeader('Access-Control-Request-Method', '*')
  44. res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET')
  45. res.setHeader('Access-Control-Allow-Headers', '*')
  46. if (req.method === 'OPTIONS') {
  47. res.writeHead(200)
  48. res.end()
  49. return
  50. }
  51. if (req.method === 'POST') {
  52. let body = ''
  53. req.on('data', (chunk) => {
  54. body += chunk.toString()
  55. })
  56. if (req.url === '/reply') {
  57. req.on('end', () => {
  58. const json = JSON.parse(body)
  59. addResponse(json)
  60. res.writeHead(200)
  61. res.end()
  62. })
  63. }
  64. if (req.url === '/error') {
  65. req.on('end', () => {
  66. res.writeHead(200)
  67. res.end()
  68. throw new Error(body)
  69. })
  70. }
  71. }
  72. })
  73. const port = 7000
  74. const server = app.listen(port)
  75. return {
  76. server,
  77. responses
  78. }
  79. }