Вот структура каталогов
resources/js/containers/Grid
├── Grid.js
├── getAllBlogsPreview.js
└── package.json
getAllBlogsPreview
импортируется в Grid
import getAllBlogsPreview from "./getAllBlogsPreview";
- это функция, которая вызывает ось и возвращает результат с некоторыми данными.
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)