[英]React & Jest: How to write a test for a component that depends on external function
图1中的组件有一个函数需要第三个参数,以便组件可以正常工作并在UI中显示数据,我为分页功能编写了单元测试。 但是,在 paginate 函数调用时缺少第三个参数时测试成功如何编写测试以在我修改 paginate.js 本身并且组件中断时提醒我?
paginate.js:
export const paginate = (posts, currentPage, numberPerPage) => {
const firstIndex = numberPerPage * currentPage;
const lastIndex = firstIndex + numberPerPage;
const currentPosts = posts.slice(firstIndex, lastIndex);
return currentPosts;
};
export const getPages = (posts, numberPerPage) => {
const numberOfPages = Math.ceil(posts.length / numberPerPage);
let pages = [];
for (let i = 0; i < numberOfPages; i++) {
pages.push(i);
}
return pages;
};
测试 paginate.js:
import { paginate, getPages } from "../utils/paginate";
describe("paginate function", () => {
it("do pagination", () => {
const posts = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15"
];
const expectedRes1 = ["1", "2", "3", "4", "5", "6"];
const expectedRes2 = ["7", "8", "9", "10", "11", "12"];
const expectedRes3 = ["13", "14", "15"];
expect(paginate(posts, 0, 6)).toEqual(expectedRes1);
expect(paginate(posts, 1, 6)).toEqual(expectedRes2);
expect(paginate(posts, 2, 6)).toEqual(expectedRes3);
expect(getPages(posts, 6)).toEqual([0, 1, 2]);
});
});
BlogContainer.js:
import React, { Component } from "react";
import BlogPost from "./BlogPost";
import CardColumns from "react-bootstrap/CardColumns";
import { paginate } from "../../utils/paginate";
export default class BlogContainer extends Component {
render() {
const currentPosts = paginate(this.props.posts, this.props.currentPage);
return (
<CardColumns>
{currentPosts.map(post => {
return (
<BlogPost
key={post.id}
title={post.title}
body={post.body}
picture="image.jpg"
></BlogPost>
);
})}
</CardColumns>
);
}
}
如果您不提供参数,它将默认为 undefined。
要解决此问题,您可以在顶部添加一个检查。
export const paginate = (posts, currentPage, numberPerPage) => {
if (!posts || !currentPage || !numberPerPage) {
// Return your error
}
...
}
它继续工作的原因是因为 numberPerPage 未定义。
const firstIndex = undefined * currentPage;
结果为 NaN
const lastIndex = NaN + numberPerPage;
结果为 NaN
const currentPosts = posts.slice(NaN, NaN);
结果是 []
return currentPosts;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.