How can I speed up the writing of tests?
import React from 'react'
import { mount } from 'enzyme'
const getNodeList = (component) => {
const nodeList = component.find('[data-el]')
return nodeList
}
const getInfoList = (nodeList) => {
const infoList = nodeList.map(node => {
const name = node.name()
const value = node.prop('data-el')
const text = node.text()
return { name, value, text }
})
return infoList
}
const getFuncList = (infoList) => {
return infoList.map(info => {
const { name, value, text } = info
switch(name) {
case 'h1': {
const methods = {
[`get${value}Text`]: () => text // (1) We can add set/get/click methods too
}
return methods
}
}
})
}
const getPageObject = (TagName, props = {}, render = mount) => {
const component = render(<TagName {...props} />)
const nodeList = getNodeList(component)
const infoList = getInfoList(nodeList)
const funcList = getFuncList(infoList)
const pageObject = { ...funcList[0] } // (2) We should iterate over this in a more generic way
return pageObject
}
export default getPageObject
const HeroPage = (props) => (
<section>
<h1 data-el='Header'>{props.text}</h1>
</section>
)
export default HeroPage
import getPageObject from './getPageObject'
import HeroPage from './HeroPage'
describe('<HeroPage /> component', () => {
it('should have correct text', () => {
const props = { text: 'hello' }
const pageObject = getPageObject(HeroPage, props)
expect(pageObject.getHeaderText()).toBe(props.text) // (3) The 'getHeaderText' was auto-magically made!
})
})
Last updated
Was this helpful?