gpt4 book ai didi

javascript - 在这种情况下,在 Jest 中测试 axios 函数的正确方法是什么?

转载 作者:行者123 更新时间:2023-11-30 06:12:40 26 4
gpt4 key购买 nike

我已经编写了一个基本的测试用例来测试我的 axios 功能。测试用例失败。我正在尝试测试一个 axios 调用,它让我得到一个 json。我格式化该数据并解析 Promise 函数。开 Jest 给出了错误,TypeError: Cannot read property 'then' of undefined

`

TypeError: 无法读取未定义的属性 'then'

  67 |                 'Authorization': `Bearer ${accessToken}`,
68 | },
> 69 | }).then((response: any): any => {
| ^
70 | if (response.statusText === "OK") {
71 | return Promise.resolve(response.data);
72 | }

`

模拟/axios.ts

export default {
get: jest.fn(() => Promise.resolve()),
request: jest.fn(() => Promise.resolve())
};

//libHelper.tsx

export default class libHelper{
constructor() {
// parameters initialization
}
}

public fetchMsGraph = (accessToken: string): Promise<GraphData> => {
return axios.get(Constants.someURL, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`,
},
}).then((response: any): any => {
if (response.statusText === "OK") {
return Promise.resolve(response.data);
}
else {
return Promise.reject(Error(`API Response not OK`));
}
}).catch((err: any): any => Promise.reject(Error(`Fetch API Error ${err}`)));

}

//libHelper-tests.tsx

import libHelper from "../Scripts/libHelper";
import axios from "../__mocks__/axios";
import { UserDataGen1, Data } from "../Scripts/interfaces";

describe("", (): void => {

test("basic test", () => {
let msalobject: MsalHelper = new MsalHelper();
expect(msalobject).toBeInstanceOf(MsalHelper);
});

test("not so basic", async () => {
const resp: UserDataGen1 = {
idp: "string",
memberName: "string",
lastName: "string",
firstName: "string",
cid: "string",
authenticatedState: "string",
picture: "string"
}
axios.get.mockImplementation(() => { Promise.resolve(resp); });

let libObject: libHelper = new libHelper();
const rand: Data = await libObject.fetchAPP("asd");

expect(rand).toEqual(resp);
});
});

最佳答案

你应该使用mockResolvedValue:

       const resp: UserDataGen1 = {
idp: "string",
memberName: "string",
lastName: "string",
firstName: "string",
cid: "string",
authenticatedState: "string",
picture: "string"
}
axios.get.mockResolvedValue(resp);

关于javascript - 在这种情况下,在 Jest 中测试 axios 函数的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57957744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com