我已经写了一个基本的测试用例来测试我的axios功能。测试用例失败。我正在尝试测试axios调用,该调用使我得到一个json。我格式化该数据并解决Promise函数。
开玩笑说出错误,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);
});
});
答案 0 :(得分:0)
您应该使用mockResolvedValue
:
const resp: UserDataGen1 = {
idp: "string",
memberName: "string",
lastName: "string",
firstName: "string",
cid: "string",
authenticatedState: "string",
picture: "string"
}
axios.get.mockResolvedValue(resp);
答案 1 :(得分:0)
这就是让它通过的原因
import mockAxios from "../__mocks__/axios";
const data: UserDataGen1 = {
idp: "string",
memberName: "string",
lastName: "string",
firstName: "string",
cid: "string",
authenticatedState: "string",
picture: "string"
}
const resp: any = {
data: data,
status: 200,
statusText: "OK",
}
mockAxios.get.mockImplementation((url: string) =>{
console.log(url);
return Promise.resolve(resp);
});