代码拆分ReactJS组件以分离API调用函数在导入提取的函数时测试失败



这是的目录结构

resources/js/containers/Grid
├── Grid.js
├── getAllBlogsPreview.js
└── package.json

getAllBlogsPreview导入到网格

import getAllBlogsPreview from "./getAllBlogsPreview";

是一个调用axis并返回带有一些数据的结果的函数。

export default function getAllBlogsPreview({ blogs = [], showGrid = false }) {
Axios.get("/api/blogs")
.then(response => {
blogs = response.data;
showGrid = false;
})
.catch(error => {
console.log(error);
});
let result = {
blogs: blogs,
showGrid: showGrid
};
return result;
}

将其移出,因为不可能使用componentDidMount方法和某些refreshTable方法直接执行这些api调用来测试组件。所以现在在组件中我有

componentDidMount() {
this.updateBlogsTable();
}
updateBlogsTable() {
let result = getAllBlogsPreview();
this.setState({ blogs: result.blogs });
this.setState({ showGrid: result.showGrid });
}

我的想法是,我应该能够模拟getAllBlogsPreview的实现,从而测试Grid,而不必拘泥于解决承诺。

测试失败,因为它试图从测试文件本身加载getAllBlogsPreview

// the component to test
import Grid from "../../containers/Grid/Grid";
import getAllBlogsPreview from "../../containers/Grid/getAllBlogsPreview";
jest.mock("getAllBlogsPreview");
describe("Blog Grid", () => {
const result = {
blogs: {
data: [
{
title: "title one",
published: false,
publish_date: null,
slug: "title-one"
}
],
links: {
self: "link-value",
first: "http://adminpanel.test/api/blogs?page=1",
last: null,
prev: null,
next: null
},
meta: {
current_page: 1,
from: 1,
path: "http://adminpanel.test/api/blogs",
per_page: 20,
to: 2
}
},
showGrid: true
};
const getAllBlogsPreviewSpy = getAllBlogsPreview;
beforeEach(() => {
getAllBlogsPreviewSpy.mockImplementation(() => result);
});
afterEach(() => {
getAllBlogsPreviewSpy.mockRestore();
});

错误

FAIL   UnitTests  resources/js/tests/Blogs/Grid.test.js
● Test suite failed to run
Cannot find module 'getAllBlogsPreview' from 'Grid.test.js'
9 | import Grid from "../../containers/Grid/Grid";
10 | import getAllBlogsPreview from "../../containers/Grid/getAllBlogsPreview";
> 11 | jest.mock("getAllBlogsPreview");
|      ^
12 | 
13 | describe("Blog Grid", () => {
14 |     const result = {
at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:276:11)
at Object.<anonymous> (tests/Blogs/Grid.test.js:11:6)

您应该模拟模块,而不仅仅是名称(它不知道模块的名称,它需要一个路径(:

jest.mock("../../containers/Grid/getAllBlogsPreview");

以下是更详细的解释:https://jestjs.io/docs/en/es6-class-mocks

相关内容

  • 没有找到相关文章

最新更新