我正在使用 Mocha + Chai 和axios-mock-adapter来测试我的 axios 请求。它运作良好,但我不知道test headers
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);
});
});
因此,如果有人知道如何为标头请求编写正确的测试,请帮助我。提前致谢!