Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Headers of Axios Request

I'm using Mocha + Chai and axios-mock-adapter for testing my axios request. It workes well, but I don't know how to test headers of axios by axios-mock-adapter and make sure Authorization and Content-type is correct!

export const uploadFile = (token: string, fileName: string, file: Buffer): Promise<string> => {
  return new Promise((resolve, reject): void => {
    const uploadFileURL = `xxxxx.com`;
    axios
      .put(uploadFileURL, file, {
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-type": "application/x-www-form-urlencoded",
        },
      })
      .then((response): void => {
        resolve(response.data.id);
      })
      .catch((error: Error): void => {
        reject(error.message);
      });
  });
};

And this is my test function

  describe("uploadFile", (): void => {
    let mockAxios: MockAdapter;
    beforeEach((): void => {
      mockAxios = new MockAdapter(axios);
    });

    afterEach((): void => {
      mockAxios.reset();
    });

    it("should return item's id", (done): void => {
      const fileName: string = faker.system.fileName();
      const token: string = faker.random.words();
      const file: Buffer = Buffer.from(faker.random.words());
      const expectedResult = {
        id: faker.random.uuid(),
      };
      mockAxios.onPut(`xxxxx.com`).reply(200, expectedResult, {
        Authorization: `Bearer ${token}`,
        "Content-type": "application/x-www-form-urlencoded",
      });

      uploadFile(token, fileName, file)
        .then((actualResult: string): void => {
          // I want to test my header of my requests
          expect(actualResult).to.equal(expectedResult.id);
          done(); // done make sure we know when we run the test
        })
        .catch(done);
    });
  });

So if anyone know how to write correct test for the header request, please help me. Thanks in advance!

like image 742
Tran B. V. Son Avatar asked Oct 11 '19 06:10

Tran B. V. Son


People also ask

How do I pass Axios with headers?

To send an Axios POST request with headers, you need to use the headers option. With axios. post() , the first parameter is the URL, the 2nd parameter is the request body, and the 3rd parameter is the options . For example, below is how you set the Content-Type header on an HTTP POST request.

Does Axios add headers?

Introduction. Axios is an HTTP client library that is used to send asynchronous HTTP requests such as POST , GET , and DELETE to REST endpoints (mainly APIs). Some of these requests, such as GET and POST , can include headers, which provide an additional source of information for each API call.

What are headers in Axios?

HTTP headers are quite simply additional information that you pass along with your HTTP request or response so that the client or the server that receives it can handle the request or response properly.


1 Answers

The only way by now is accessing request headers in .reply and validate it here:

mockAxios.onPut(`xxxxx.com`).reply((config) => {
  expect(config.headers."Content-Type").toEqual("What do you expect here");
  return [200, expectedResult, {
    Authorization: `Bearer ${token}`,
    "Content-type": "application/x-www-form-urlencoded",
  }];
});

Actually I believe it should also be possible in declarative way:

mockAxios.onPut(`xxxxx.com`, undefined, { 
  expectedHeader1: "value1", 
  expectedHeader2: "value2"}
).reply(200, expectedResult);

So it would just throw instead of returning mock response if request headers did not match.

But it does no work this way by now.

Reason: axios-mock-adapter uses deepEqual for such a filtering. So we would need specify there not just few required headers(we are focusing on) but all headers including those axios adds on its own(like Accept). So it is not really readable.

I've filed #219 in their repo on this. If it was not intentional for any reason, that may be fixed in future.

like image 156
skyboyer Avatar answered Oct 14 '22 11:10

skyboyer