app-test-setup.js 2.1 KB

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