Last active
December 3, 2016 19:06
-
-
Save cecilemuller/9bb4e1f01b44d7d68c61ca981c7c6e43 to your computer and use it in GitHub Desktop.
Preact: setState without Enzyme
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/* eslint-env mocha, browser */ | |
const assert = require('assert'); | |
const {h, render, Component} = require('preact'); | |
class TestableComponent extends Component { | |
componentDidMount(){ | |
if (this.props.testable){ | |
this.props.testable(this); | |
} | |
} | |
} | |
class MyComponent extends TestableComponent { | |
constructor(){ | |
super(); | |
this.state = { | |
hello: 'Initially', | |
mounted: false | |
}; | |
} | |
componentDidMount(){ | |
this.setState({ | |
mounted: true | |
}); | |
super.componentDidMount(); // This is the one requirement for TestableComponent to work | |
} | |
render(props, state){ | |
return h('h1', null, state.hello); | |
} | |
} | |
function set_state_without_enzyme(done){ | |
document.body.innerHTML = ''; | |
const element = h(MyComponent, { | |
testable: component => { | |
// Initial state | |
assert.strictEqual(component.state.hello, 'Initially'); | |
assert.strictEqual(document.body.firstChild.childNodes[0].nodeValue, 'Initially'); | |
// The change being tested | |
component.setState({hello: 'Updated'}); | |
// Updated state | |
setTimeout(() => { | |
assert.strictEqual(component.state.hello, 'Updated'); | |
assert.strictEqual(document.body.firstChild.childNodes[0].nodeValue, 'Updated'); | |
done(); | |
}); | |
} | |
}); | |
render(element, document.body); | |
} | |
describe('Tests', () => { | |
it('setState without Enzyme', set_state_without_enzyme); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update: you can now use package @wildpeaks/preact-component-testable.