我正在使用Mocha + Chai以及axios-mock-adapter来测试我的axios请求。它工作得很好,但我不知道如何通过axios-mock-adapter测试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);
});
});
};
这是我的测试函数
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);
});
});
如果有人知道如何编写正确的标题请求测试,请帮助我。提前感谢!
[200,expectedResult]
,因为在uploadFile
中,我们同时使用了授权和“Content-type”。但无论如何,回答得很好! - Tran B. V. Sonthen
链中是否有什么依赖于响应中存在的标头。但是当然,如果你不需要那个,你就不需要它。 - skyboyer