我正在使用 Mocha + Chai 和 axios-mock-adapter用于测试我的 axios 请求。它工作得很好,但我不知道如何通过 axios-mock-adapter 测试 axios 的 headers 并确保 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);
});
});
因此,如果有人知道如何为 header 请求编写正确的测试,请帮助我。提前致谢!
最佳答案
目前唯一的方法是访问 .reply
中的请求 header 并在此处进行验证:
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);
因此,如果请求 header 不匹配,它只会抛出而不是返回模拟响应。
但现在这种方式还行不通。
原因:axios-mock-adapter
使用 deepEqual
进行此类过滤。因此,我们需要指定的不仅仅是少数必需的 header (我们关注的),而是所有 header ,包括那些 axios 添加的 header (例如 Accept
)。所以它并不是真正可读。
我已经filed #219在他们的 repo 协议(protocol)中。如果出于任何原因不是故意的,将来可能会修复。
关于javascript - 测试 axios 请求的 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58335115/