[英]Testing Headers of Axios Request
我正在使用 Mocha + Chai 和axios-mock-adapter来测试我的 axios 请求。 它运行良好,但我不知道如何通过 axios-mock-adapter test headers
axios 的标头并确保Authorization
和Content-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);
});
});
};
这是我的测试 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);
});
});
因此,如果有人知道如何为 header 请求编写正确的测试,请帮助我。 提前致谢!
现在唯一的方法是访问.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",
}];
});
实际上我相信它也应该以声明的方式是可能的:
mockAxios.onPut(`xxxxx.com`, undefined, {
expectedHeader1: "value1",
expectedHeader2: "value2"}
).reply(200, expectedResult);
因此,如果请求标头不匹配,它只会抛出而不是返回模拟响应。
但现在这种方式行不通。
原因: axios-mock-adapter
使用deepEqual
进行此类过滤。 因此,我们不仅需要指定几个必需的标头(我们正在关注),还需要指定所有标头,包括 axios 自己添加的所有标头(例如Accept
)。 所以它不是真正可读的。
我已经在他们的回购中提交了#219 。 如果出于任何原因不是故意的,将来可能会修复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.