Search code examples
node.jsjestjsfastify

How to upload file using fastifyInstance server.inject


I am trying to test file upload functionality the end point internally uploads the image to azure blob container and returns the image url.

Is there any way to upload the file using server.inject?

How to mock the azureBlob.js file?

upload.test.js

it("should return 200", async () => {
      const response = await server.inject({
        method: "POST",
        url: `/Store/${StoreID}/logo`,
        headers,
        payload: {
          file: file????,
        },
      });
      expect(response.statusCode).toBe(200);
    });

the "/Store/${StoreID}/logo" end point internally calls azureBlob file for uploading file to azure blob container.

azureBlob.js

export const uploadFileToBlob = async (file: File): Promise<string> => {
  if (!file) return "";

  const blobService = await BlobServiceClient.fromConnectionString(
    connectionString
  );

  // get Container - full public read access
  const containerClient: ContainerClient = blobService.getContainerClient(
    blobContainerName ?? ""
  );

  await containerClient.createIfNotExists({
    access: "container",
  });

  // upload file
  await createBlobInContainer(containerClient, file);

  return imageurl;
};

Solution

  • The server.inject method uses light-my-request under the hood, so you can use all its options.

    I built the form-auto-content module to let the user submit to an API a form:

    const formAutoContent = require('form-auto-content')
    
    
    const myForm = formAutoContent({
      myFile: fs.createReadStream('the-file.xml'),
    })
    
    server.inject({
      url: '/upload',
      ...myForm
    })