Jest + React:在函数中模拟道具

时间:2018-02-20 13:43:49

标签: reactjs jestjs

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

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

sortFunction = cellDataKey => {
  let changeSortDirection;

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

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

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

谢谢!(:

1 个答案:

答案 0 :(得分:0)

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

// 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
相关问题