Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Last active December 3, 2016 19:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cecilemuller/9bb4e1f01b44d7d68c61ca981c7c6e43 to your computer and use it in GitHub Desktop.
Save cecilemuller/9bb4e1f01b44d7d68c61ca981c7c6e43 to your computer and use it in GitHub Desktop.
Preact: setState without Enzyme
'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);
});
@cecilemuller
Copy link
Author

Update: you can now use package @wildpeaks/preact-component-testable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment