typescript 类型错误:axios.get 不是函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52396724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: axios.get is not a function?
提问by Leon Gaban
Not sure why I'm getting the following error:
不知道为什么我收到以下错误:
TypeError: axios.get is not a function
4 |
5 | export const getTotalPayout = async (userId: string) => {
> 6 | const response = await axios.get(`${endpoint}get-total-payout`, { params: userId });
7 | return response.data;
8 | };
9 |
My service:
我的服务:
import * as axios from 'axios';
const endpoint = '/api/pool/';
export const getTotalPayout = async (userId: string) => {
const response = await axios.get(`${endpoint}get-total-payout`, { params: userId });
return response.data;
};
My jest test:
我的笑话测试:
// import mockAxios from 'axios';
import { getTotalPayout } from './LiquidityPool';
const userId = 'foo';
describe('Pool API', () => {
it('getTotalPayout is called and returns the total_payout for the user', async () => {
// mockAxios.get.mockImplementationOnce(() => {
// Promise.resolve({
// data: {
// total_payout: 100.21,
// },
// });
// });
const response = await getTotalPayout(userId);
console.log('response', response);
});
});
In the src/__mocks__/axios.js I have this:
在 src/__mocks__/axios.js 我有这个:
// tslint:disable-next-line:no-empty
const mockNoop = () => new Promise(() => {});
export default {
get: jest.fn(() => Promise.resolve({ data: { total_payout: 100.21 }})),
default: mockNoop,
post: mockNoop,
put: mockNoop,
delete: mockNoop,
patch: mockNoop
};
回答by tyskr
Please look at: MDN
请看:MDN
As mentoined there, you need a value to collect the default export
and the rest as X
. In this case you could:
正如那里提到的,您需要一个值来收集default export
和 其余的X
。在这种情况下,您可以:
import axios, * as others from 'axios';
X being others
here.
X在others
这里。
Instead of
代替
import * as axios from 'axios';
Assumption: ... from 'axios'
is referring to your jest mock. Let me know if that answers your question.
假设:... from 'axios'
指的是你的玩笑模拟。如果这能回答您的问题,请告诉我。
回答by basarat
You have import * as axios from 'axios';
. In this case axios
is not a default export. Your mock assumes it is so:
你有import * as axios from 'axios';
。在这种情况下axios
是不是默认的出口。你的模拟假设是这样:
export default {
get: jest.fn(() => Promise.resolve({ data: { total_payout: 100.21 }})),
default: mockNoop,
post: mockNoop,
put: mockNoop,
delete: mockNoop,
patch: mockNoop
};
Fix
使固定
Remove the default export and replace your mock structure to map the export structure of axios as you are using it.
删除默认导出并替换您的模拟结构以在您使用 axios 时映射它的导出结构。