单元测试无状态组件方法 [英] unit test stateless component method
问题描述
我有这个无状态的 react 组件
I have this stateless component of react
const Clock = () => {
const formatSeconds = (totalSeconds) => {
const seconds = totalSeconds % 60,
minutes = Math.floor(totalSeconds / 60)
return `${minutes}:${seconds}`
}
return(
<div></div>
)
}
export default Clock
如何测试 formatSeconds 方法?
How to test formatSeconds method?
我写了这个,但测试失败了.
I wrote this, which the test has failed.
import React from 'react'
import ReactDOM from 'react-dom'
import expect from 'expect'
import TestUtils from 'react-addons-test-utils'
import Clock from '../components/Clock'
describe('Clock', () => {
it('should exist', () => {
expect(Clock).toExist()
})
describe('formatSeconds', () => {
it('should format seconds', () => {
const Clock = TestUtils.renderIntoDocument(<Clock />)
const seconds = 615
const expected = '10:15'
const actual = Clock.formatSeconds(seconds)
expect(actual).toBe(expected)
})
})
})
第一个测试通过了,但可能在执行 Clock.formatSeconds 时出现了一些问题.
The first test passed but maybe there's some problem doing Clock.formatSeconds.
推荐答案
组件 Clock
是一个函数,在组件渲染时调用.formatSeconds
方法定义在Clock
闭包内部,它不是Clock
的属性,因此您无法从外部访问它.
The component Clock
is a function, which is invoked when the component is rendered. The method formatSeconds
is defined inside the the Clock
closure, and it's not a property of Clock
, so you can't reach it from outside.
此外,您在每次渲染时都重新创建了 formatSeconds
方法,并且由于该方法实际上并未在范围内使用任何道具,因此有点浪费.因此,您可以将方法取出并导出.您也可以将它移动到另一个实用程序文件,然后导入它,因为它不是 Clock
的组成部分,您可能希望在其他地方重复使用它.
In addition, you are recreating the formatSeconds
method on every render, and since the method doesn't actually use any prop in the scope, it's a bit wasteful. So, you can take the method out, and export it. You can also move it to another utility file, and import it, since it's not an integral part of Clock
, and you might want to reuse it other places.
export const formatSeconds = (totalSeconds) => {
const seconds = totalSeconds % 60,
minutes = Math.floor(totalSeconds / 60)
return `${minutes}:${seconds}`
}
const Clock = () => {
return(
<div></div>
)
}
export default Clock
现在测试也很容易:
import React from 'react'
import ReactDOM from 'react-dom'
import expect from 'expect'
import TestUtils from 'react-addons-test-utils'
import Clock, { formatSeconds } from '../components/Clock' // import formatSeconds as well
describe('Clock', () => {
it('should exist', () => {
expect(Clock).toExist()
})
describe('formatSeconds', () => {
it('should format seconds', () => {
const seconds = 615
const expected = '10:15'
const actual = formatSeconds(seconds) // use it by itself
expect(actual).toBe(expected)
})
})
})
这篇关于单元测试无状态组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!