components-state-testing.mo
Owner: Tycho Tatitscheff
Prerequisites (~5 min)
Steps (~30 min)
Create a simple test:
describe('ComponentToTest', () => { it('should test a simple true === true', () => { expect(true).toBe(true); }); });
Import the necessary packages and your component:
```javascript
import React from 'react';
import renderer from 'react-test-renderer';
import ComponentToTest from './ComponentToTest.component';
- Add the first test of your component, and remove the true === true
- Render your component with react-test-renderer, it will transform your component in a JavaScript object instance, which you will be able to test, accessing its state, triggering its methods:
```javascript
describe('ComponentToTest', () => {
const props = {};
const component = renderer.create(
<ComponentToTest
props={props}
/>
);
//...
});
Use this instance in your
it
test, the propertygetInstance()
allows you to access all the properties of the component class. Now you can test your initial state:describe('ComponentToTest', () => { // ... it('should init the state', () => { expect(component.getInstance().state).toEqual({ fakeStatus: 'init', }); }); });
Add new tests, faking a user action and the impact it has on the component state:
describe('ComponentToTest', () => { // ... it('should set the component fakeStatus to "inProgress"', () => { component.getInstance().onButtonPress(); expect(component.getInstance().state).toEqual({ fakeStatus: 'inProgress', }); }); // ... });
Last updated