【问题标题】:Jest + React: Mocking props in a functionJest + React:在函数中模拟道具
【发布时间】:2018-02-20 22:39:30
【问题描述】:

所以我之前没有过多地使用 React 尝试过 Jest,并且从一开始就很好奇如何测试一些东西。

例如:我有一个排序功能:

sortFunction = cellDataKey => {
  let changeSortDirection;

  const {
    sortBy,
    sortDirection,
    dataSource
  } = this.props;

  if (cellDataKey === sortBy) {
  ....

我很好奇如何测试这样的东西,我应该模拟props吗?或者以某种方式重构以下函数?

谢谢!(:

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:

    如果你的函数没有副作用,也没有外部依赖,看起来,这很容易。您只需使用测试数据调用函数并将返回值与预期值进行比较,如下所示(假设函数在其自己的文件中导出和隔离):

    // Let's call this file sortFunction.test.js
    import sortFunction from './sortFunction'
    
    describe('A function to sort them all', () => {
      test('It returns sorted values', () => {
        let myTestData = [6, 5, 4, 3, 2, 1]
        expect(sortFunction(myTestData)).toEqual([1, 2, 3, 4, 5, 6])
      })
    })
    

    使用jest 运行测试后,测试将失败或通过,您将看到输出。

    更新:

    如何使用组件中的函数(通常您会将函数和其他实用程序放在某个专用文件夹中,例如libutil):

    import React, { Component } from 'react'
    import sortFunction from './sortFunction'
    
    class Table extends Component {
        constructor(props) {
            super(props)
            this.state = {
                values: sortFunction(this.state.values)
            }
        }
        render() {
            return (
                <div>
                { this.state.values.map(value => (
                    <div>{value}</div>
                )) }
                </div>
            )
        }
    }
    
    export default Table
    

    【讨论】:

    • 但是例如,如果sortFunction 需要来自Table 组件道具的数据,我将如何解决这个问题?
    • 您的意思是如何使用Table 组件中的函数,或者如何使用 组件对其进行测试?
    • 这两个选项听起来都很有趣,但首先我想到了第一个
    • 检查上面的添加。
    猜你喜欢
    • 1970-01-01
    • 2019-09-12
    • 2019-07-22
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 2018-01-12
    相关资源
    最近更新 更多