如果你的函数没有副作用,也没有外部依赖,看起来,这很容易。您只需使用测试数据调用函数并将返回值与预期值进行比较,如下所示(假设函数在其自己的文件中导出和隔离):
// 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 运行测试后,测试将失败或通过,您将看到输出。
更新:
如何使用组件中的函数(通常您会将函数和其他实用程序放在某个专用文件夹中,例如lib 或util):
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