execute.test.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import request from 'supertest';
  2. import express from 'express';
  3. import { jest } from '@jest/globals';
  4. import execute from '../execute';
  5. let delta = 0;
  6. // Fake date
  7. jest.spyOn(global.Date, 'now').mockImplementation(() => {
  8. delta += 1;
  9. const second = delta < 10 ? '0' + delta : '' + delta;
  10. return new Date(`2020-03-14T11:01:${second}.135Z`).valueOf();
  11. });
  12. describe('Execute Test', () => {
  13. let app;
  14. let query;
  15. let execFunction;
  16. beforeAll(() => {
  17. app = express();
  18. app.use(express.json());
  19. execFunction = jest.fn(({ body, method, query, id, response }) => {
  20. const result = { hello: true, method, query, body, console, id };
  21. try {
  22. result.response = response;
  23. } catch {
  24. console.log('-');
  25. }
  26. return result;
  27. });
  28. const functions = { mytestfunction: execFunction };
  29. app.use(execute({ functions }));
  30. query = request(app);
  31. });
  32. it('should execute remote function', async () => {
  33. await query.get(`/execute/missingfunction`).expect(404);
  34. const result = await query.get(`/execute/mytestfunction/`).expect(200);
  35. expect(result.body).toEqual(expect.objectContaining({ hello: true }));
  36. expect(result.body.method).toBe('GET');
  37. const result2 = await query
  38. .post(`/execute/mytestfunction`)
  39. .set('X-SPC-Host', 'http://localhost:5000/')
  40. .send({ test: 42 })
  41. .expect(200);
  42. expect(result2.body.method).toBe('POST');
  43. expect(result2.body.body).toEqual(expect.objectContaining({ test: 42 }));
  44. });
  45. it('should run remote function with id', async () => {
  46. const result = await query.get(`/execute/mytestfunction/42`).expect(200);
  47. expect(result.body).toEqual(expect.objectContaining({ id: '42' }));
  48. });
  49. });