React Component Testing
Nov 11, 2020
This post introduces how to test react component
There are broadly 2 approaches
Mocha, Chai, Sinon + Enzyme: If you are coming from a Node.js environment.
Jest + Enzyme/React Testing Library: If you want to test the more idiomatic way.
- Testing DOM elements
- Testing events
- Testing asynchronous actions
- Testing React Redux
- Testing React Context
- Testing React Router
- Testing HTTP Request
A11y
I want to trigger mouseover, mouseup, mousedown and click
document.querySelector('h2').dispatchEvent(new Event('mouseover'))expect(document.querySelector('span[dir=ltr] span').style.cssText).to.contain('translateX')
const isA11y = html =>
new Promise((resolve, reject) => {
axe.run(html, {}, (err, result={}) => {
const { violations=[] } = result
if (err) {
reject(err)
} else if (violations.length > 0) {
reject(violations)
} else {
// Uncomment to view incomplete/unavailable tests & why
//console.log(result.incomplete)
resolve(true)
}
})
})
it('bad form', async () => {
const wrap = document.createElement('div')
wrap.innerHTML = `
<form>
<div>Enter your name</div>
<input type="text" />
<button type="submit">Submit</button>
</form>
`
document.body.appendChild(wrap)
// expect(await isA11y(wrap)).toEqual(true)
})