测试 Axios 请求的标头

Tra*_*Son 6 javascript node.js axios axios-mock-adapter

我正在使用 Mocha + Chai 和axios-mock-adapter来测试我的 axios 请求。它运行良好,但我不知道如何test headers通过 axios-mock-adapter来使用 axios 并确保AuthorizationContent-type是正确的!

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);
      });
  });
};
Run Code Online (Sandbox Code Playgroud)

这是我的测试功能

  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);
    });
  });
Run Code Online (Sandbox Code Playgroud)

因此,如果有人知道如何为标头请求编写正确的测试,请帮助我。提前致谢!

sky*_*yer 7

现在唯一的方法是访问请求标头.reply并在此处验证它:

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",
  }];
});
Run Code Online (Sandbox Code Playgroud)

其实我相信它也应该以声明的方式成为可能:

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

因此,如果请求标头不匹配,它只会抛出而不是返回模拟响应。

但现在这种方式不起作用。

原因是:axios-mock-adapter使用deepEqual这种过滤。因此,我们不仅需要指定几个必需的标头(我们关注),而且还需要指定所有标头,包括那些 axios 自己添加的(如Accept)。所以它不是真的可读。

我已经在他们的 repo 中提交了#219。如果出于任何原因不是故意的,那么将来可能会修复。