app-test-setup.js 2.0 KB

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