test-utils.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import httpMocks from 'node-mocks-http';
  2. import { EventEmitter } from 'node:events';
  3. import { loadFixture as baseLoadFixture } from '../../../astro/test/test-utils.js';
  4. process.env.ASTRO_NODE_AUTOSTART = 'disabled';
  5. process.env.ASTRO_NODE_LOGGING = 'disabled';
  6. /**
  7. * @typedef {import('../../../astro/test/test-utils').Fixture} Fixture
  8. */
  9. export function loadFixture(inlineConfig) {
  10. if (!inlineConfig?.root) throw new Error("Must provide { root: './fixtures/...' }");
  11. // resolve the relative root (i.e. "./fixtures/tailwindcss") to a full filepath
  12. // without this, the main `loadFixture` helper will resolve relative to `packages/astro/test`
  13. return baseLoadFixture({
  14. ...inlineConfig,
  15. root: new URL(inlineConfig.root, import.meta.url).toString(),
  16. });
  17. }
  18. export function createRequestAndResponse(reqOptions) {
  19. let req = httpMocks.createRequest(reqOptions);
  20. let res = httpMocks.createResponse({
  21. eventEmitter: EventEmitter,
  22. req,
  23. });
  24. let done = toPromise(res);
  25. // Get the response as text
  26. const text = async () => {
  27. let chunks = await done;
  28. return buffersToString(chunks);
  29. };
  30. return { req, res, done, text };
  31. }
  32. export function toPromise(res) {
  33. return new Promise((resolve) => {
  34. // node-mocks-http doesn't correctly handle non-Buffer typed arrays,
  35. // so override the write method to fix it.
  36. const write = res.write;
  37. res.write = function (data, encoding) {
  38. if (ArrayBuffer.isView(data) && !Buffer.isBuffer(data)) {
  39. data = Buffer.from(data.buffer);
  40. }
  41. return write.call(this, data, encoding);
  42. };
  43. res.on('end', () => {
  44. let chunks = res._getChunks();
  45. resolve(chunks);
  46. });
  47. });
  48. }
  49. export function buffersToString(buffers) {
  50. let decoder = new TextDecoder();
  51. let str = '';
  52. for (const buffer of buffers) {
  53. str += decoder.decode(buffer);
  54. }
  55. return str;
  56. }
  57. export function waitServerListen(server) {
  58. return new Promise((resolve) => {
  59. server.on('listening', () => {
  60. resolve();
  61. });
  62. });
  63. }