[英]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.