如何在指定的导出react功能组件中正确导入和测试功能?

时间:2019-10-29 20:54:29

标签: reactjs jestjs

我的应用是使用create-react-app创建的,因此应该可以与jest一起使用。我正在尝试对功能组件中的功能进行测试。运行“ npm测试”时,测试无法显示

    TypeError: chatlist.randoColor is not a function

我尝试默认导出并按以下方式导入:

    import { Chatlist } from '../Components/ChatList';
    const randoColor = require('../Components/ChatList');
    import randoColor from '../Components/ChatList';

但是,所有人似乎都无法识别组件中找到的任何功能。理想情况下,我想将其保留为已命名的出口,但欢迎所有建议。对于类似这样的功能,也可能会在其自己的实用程序文件中建议使用该功能,但是我也想在组件中包含其他功能,而我也想在不将所有功能存储在实用程序文件中的情况下进行导入和测试。

这是我的项目目录结构。

src
| __tests__
  | ChatList.test.js
| Components
  | ChatList.js

我想为在我的ChatList组件randoColor中找到的一个函数(或任何真正的函数)编写一个测试。

export const ChatList = ({ chats }) => {
  const randoColor = max => Math.floor(Math.random() * Math.floor(max));
   if (chats.length > 0) {
    return <main></main
}

这是我的ChatList.test.js文件。

import * as chatlist from '../Components/ChatList';

describe('<Chatlist />', () => {
  test('randoColor fn should generate a random number given a max input', () => {
    expect(chatlist.randoColor(230)).not.toBeNaN();
  });
});

预期结果是npm测试成功运行,检测到功能并通过的结果。实际结果是:         TypeError:chatlist.randoColor不是函数

1 个答案:

答案 0 :(得分:2)

randoColor仅存在于方法ChatList的范围内,因此无法从外部进行访问。另外最好只通过道具访问反应组件。

由于该方法未使用任何ChatList道具,因此建议将其移至该方法之外。喜欢:

const ChatList = ({ chats }) => { 
   if (chats.length > 0) {
       return <main></main
   }
}
ChatList.randoColor = max => Math.floor(Math.random() * Math.floor(max))
export default ChatList

可以像这样访问

import ChatList from '../Components/ChatList'
ChatList.randoColor(230)

我建议将该函数移动到其他地方,例如创建utils文件夹,并使用此方法以及与颜色相关的其他方法将其类似于utils / colorUtils.js。这样一来,<ChatList />组件就变得更加干净,唯一可以更改的方法就是通过props或Context。

我也将export ChatList更改为export default ChatList,以便您无需访问{ }