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
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)
})
})
})
The first test passed but maybe there's some problem doing Clock.formatSeconds.
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.
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
Now testing is easy as well:
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)
})
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With