Jest说TypeError:(0,className.functionName)不是函数
我有一个JS文件如下
import axios from "axios";
export default class SomeService {
static getSomething(id) {
return axios
.get(API_BASE_URL + API_URL_Something, {
params: { id: id},
})
.then((result) => {
return result.data;
})
.catch((error) => {
throw error;
});
}
}
,并且有一个test.js使用开玩笑如下,
import axios from "axios";
import { getSomething } from "../SomeService.js";
jest.mock("axios");
describe("getSomething", () => {
describe("when API call is successful", () => {
it("should return some details", () => {
// given
const someDetails = [
{ id: 1, name: "Something 1" },
{ id: 2, name: "Something 2" },
];
axios.get.mockResolvedValueOnce(someDetails);
// when
const result = getSomething(123); // ERROR THROWN HERE
// then
let url = API_BASE_URL + Constants.API_URL_Something;
expect(axios.get).toHaveBeenCalledWith(`${url}`);
expect(result).toEqual(someDetails);
});
});
describe("when API call fails", () => {
it("should return empty entity details", () => {
// ...
});
});
});
但是当我运行NPM测试时,我会收到此错误,
TypeError: (0 , _SomeService.getSomething) is not a function
我尝试过将功能不静态(我不必),尝试将其导出(cann也许是正确的),但不能使它变得非常努力。其他类似的帖子也不能解决我的问题。我在做什么错?
I have a js file as follows
import axios from "axios";
export default class SomeService {
static getSomething(id) {
return axios
.get(API_BASE_URL + API_URL_Something, {
params: { id: id},
})
.then((result) => {
return result.data;
})
.catch((error) => {
throw error;
});
}
}
And I have a test.js using jest as follows
import axios from "axios";
import { getSomething } from "../SomeService.js";
jest.mock("axios");
describe("getSomething", () => {
describe("when API call is successful", () => {
it("should return some details", () => {
// given
const someDetails = [
{ id: 1, name: "Something 1" },
{ id: 2, name: "Something 2" },
];
axios.get.mockResolvedValueOnce(someDetails);
// when
const result = getSomething(123); // ERROR THROWN HERE
// then
let url = API_BASE_URL + Constants.API_URL_Something;
expect(axios.get).toHaveBeenCalledWith(`${url}`);
expect(result).toEqual(someDetails);
});
});
describe("when API call fails", () => {
it("should return empty entity details", () => {
// ...
});
});
});
But when I run npm test I get this error
TypeError: (0 , _SomeService.getSomething) is not a function
I have tried making the function non static (I shouldn't have to), tried exporting it (couldn't get the syntax right perhaps), but can't get it to quite work. Other similar posts do not solve my issue either. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据我在代码中看到的内容,您正在导出类
someService
,而不是其内部getsomething
方法。因此,您肯定需要将测试代码更改为以下内容:From what I can see in your code you are exporting the class
SomeService
, not its internalgetSomething
method. So surely you need to change your test code to something like the following: