dce-enzyme
React component unit testing package that wraps Enzyme.
Writing a Test
Import dependencies at top of test
import React from 'react';
import Driver from 'dce-enzyme';
Write your test
Initialize the driver with the component to test then use driver functions (see the full list below) to write your test
...
import OkayButton from './OkayButton';
describe('OkayButton', () => {
it('Handles a Click', async () => {
// Keep track of button clicks
let clicked = false;
// Initialize the driver
const driver = new Driver(
<OkayButton
title="I am Done"
color="blue"
onClick={() => { clicked = true; }}
/>
);
// Simulate a click
await driver.click('button');
// Make sure the button was clicked
assert(clicked, 'The button did not call onClick');
});
});
Driver functions
Note: wherever you see "selector," this can be a CSS selector, React component constructor, React component display name, object property selector, or any other valid enzyme selector.
click(selector) – clicks the given element
Example:
driver.click('#close-button');
focus(selector) - focuses the given element
Example:
driver.click('#selectable-element');
toggleCheckbox(selector) - simulates someone toggling a checkbox
Example:
driver.toggleCheckbox('#agree');
typeInto(selector, text) – types the given text into the element
Example:
await driver.typeInto('#email-field', 'example@harvard.edu');
getAttributes(selector) – returns an object holding all the attributes of the element
Example:
const att = driver.getAttributes('#email-field');
const email = att.value;
assert(email.includes('@'), 'Email does not include "@"');
getHTML(selector) – returns the HTML representation of the element
Example:
const html = driver.getHTML('#okay-button');
assert(html.includes('some-html-content'));
elementExists(selector) – returns true if the given element exists
Example:
assert(driver.elementExists('#submit'), 'Submit button absent');
getText(selector) – returns the text inside an element
Example:
assert.equal(
driver.getText('span'),
'About Me',
'Span text was incorrect'
);
getState() – returns the state of the root-level component
Example:
const state = driver.getState();
assert.equal(
state.numClicks,
10,
'The number of clicks in the state is wrong!'
);
waitForElementToExist(selector, [timeoutSecs = 2]) – waits for an element to exist
Waits until the element exists.
waitForStatePropToEqual(prop, value, [timeoutSecs = 2]) – waits for a property of the root-level component's state to equal the given value
Arguments:
- prop – the state property to check
- value – wait for the prop to equal this value
- timeoutSecs – the number of seconds to wait until throwing a timeout error
Example:
// Wait up to 1min for the component to load
await driver.waitForStatePropToEqual('status', 'loaded', 60);