lundi 25 juin 2018

Testing DOM in Enzyme

Let's say I have a tiny component like this:

Button.js

import React from 'react';
import './Button.css';

export default class Button extends React.Component {
  render() {
    return (
      <a href={ this.props.url } className={`button button-${ this.props.type }`}>
        { this.props.content }
      </a>
    );
  }
}

And there's some super basic styling like this:

Button.css

.button {
  color: white;
  padding: 1em;
  border-radius: 5px;
  text-decoration: none;
}

.button-primary {
  background-color: red;
}
.button-primary:hover {
  background-color: darkred
}

.button-secondary {
  background-color: aqua;
  color: black;
}
.button-secondary:hover {
  background-color: darkcyan;
  color: white;
}

And let's say I want to write some tests for this:

Button.test.js

import React from 'react';
import Enzyme, {shallow, mount} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({adapter: new Adapter()});

import Button from './Button';
import './Button.css';

// Render buttons
const primaryButton = mount(
  <Button 
    content="Primary button" 
    url="http://www.amazon.co.uk"
    type="primary"
  />
);
const secondaryButton = mount(
  <Button 
    content="Secondary button" 
    url="http://www.ebay.co.uk"
    type="secondary"
  />
);

it('should exist', () => {
  expect(primaryButton).toBeDefined();
  expect(secondaryButton).toBeDefined();
});

it('should display text in the button', () => {
  expect(primaryButton.text()).toEqual('Primary button');
});

it('should have the correct CSS classes', () => {
  expect(primaryButton.find('.button').hasClass('button-primary')).toEqual(true);
  expect(secondaryButton.find('.button').hasClass('button-secondary')).toEqual(true);
});

I've set this up using react-create-app and all the above works perfectly.

My question is: how do I test that what is getting rendered looks correct? For example, in this case I would want to make sure that the buttons have the correct background colours defined in the CSS file and that they have the correct border radius. This will prevent other developers accidentally overriding critical styling for example.

I was under the impression that Enzyme did this out of the box, but I cannot understand how to interrogate the virtual DOM which I assume is happening in the background? I thought that JSDOM was automatically running and I'm executing this from the CLI which is a Node environment.

Aucun commentaire:

Enregistrer un commentaire