簡體   English   中英

React & Jest:如何為依賴於外部函數的組件編寫測試

[英]React & Jest: How to write a test for a component that depends on external function

BlogContainer 組件代碼

圖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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM