npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-component-setup

v0.3.1

Published

A react component test helper

Downloads

4

Readme

react-component-setup

Build Status Coveralls github

Description

This package reduces component testing boilerplate code by providing a handy mount and shallow functions using enzyme.

Installation

Run the following command:

npm install --save-dev react-component-setup

Why?

I read an article by Tomasz Bak describing some best react practices. One practice described that you should use a setup() instead of a beforeEach (in jest) for your code to be more readable. I liked this practice and incorporated into one of my projects. However, immediately, it became tedious to write a setup() for every component; thus I created react-component-setup.

Usage

First, install the required packages!

Import the package:

import { SetupComponent } from 'react-component-setup';

Then run the SetupComponent initially in your Reactjs test file to generate default properties and automatic element fetching.

SetupComponent will return an object with mount and shallow functions. Each of which corresponds with their respective enzyme call. Example return:

{
    mount: [mount Function],
    shalllow: [shallow Function]
}
import React, { Component } from 'react';
import { SetupComponent } from 'react-component-setup';

class CoolReactComponent extends Component {
    render() {
        return (
            <div>
                <h1>Hello, world!</h1>
                <p>I am a cool react component</p>
            </div>
        );
    }
}

const { shallow: setup } = SetupComponent({ component: CoolReactComponent }); // Component to construct
// I could have used mount instead of shallow if needed

Note that the { shallow: setup } = ... is just a javascript object deconstructor.

Then add a simple test using whatever testing framework you want, in this case, I used jest.

describe('CoolReactComponent', () => {
    it('should render a cool component', () => {
        const { wrapper } = setup();
        expect(wrapper.exists()).toBe(true);
    });
});

Both mount and shallow return an object of wrapper which is the enzyme shallow container of the constructed component.

Defining properties for the component

Most components have properties. In order to supply your properties to the component provide an object with the properties value. Example:

import React, { Component } from 'react';
import { SetupComponent } from 'react-component-setup';

class NameDisplayer extends Component {
    render() {
        return (
            <h1>First name: {this.props.firstName}. Last name: {this.props.lastName}.</h1>
        );
    }
}

const { shallow: setup } = SetupComponent({ component: NameDisplayer });

setup({
    firstName: 'Mark'
    lastName: 'Johnson'
}); // returns component like <h1>First name: Mark. Last name: Johnson.</h1>

Find an element automatically

If you want to find an element automatically (you test that element quite often) You can add it to the SetupComponent's elementsToFind list. All elementsToFind does is it returns the wrapper.find() of the query using the name. Example:

import React, { Component } from 'react';
import { SetupComponent } from 'react-component-setup';

class CoolReactComponent extends Component {
    render() {
        return (
            <div>
                <h1>Hello, world!</h1>
                <p className="cool-paragraph">I am a cool react component</p>
            </div>
        );
    }
}

const { shallow: setup } = SetupComponent({
    component: CoolReactComponent,
    elementsToFind: [ // the elements that should be found automatically
        {
            name: 'coolParagraph',
            query: '.cool-paragraph'
        }
    ]
});

describe('CoolReactComponent', () => {
    it('should render a chill paragraph', () => {
        const { coolParagraph } = setup(); // coolParagraph is from the name in the list
        expect(coolParagraph.html()).toMatchSnapshot();
    });
});

Refreshing elements in elementsToFind

I have had trouble using elementsToFind with inputs when simulating a change. Simulating a change on input causes any variable reference to the element to become stale, thus the variable is useless since you will need to reuse the wrapper.find method. See more here. To fix this issue a newly created refresh method has been added to automatically refind the element for you.

Basic Example:

const { wrapper, coolCustomElementToFind, refresh } = setup(); // setup is the the shallow or mount function created from SetupComponent

const refreshedCustomElement = refresh(coolCustomElementToFind); // refresh does not change coolCustomElementToFind

Full Example:

import React, { Component } from 'react';
import { SetupComponent } from 'react-component-setup';

class InputComponent extends Component {

  state = {
    val: 'unchanged'
  };

  changeVal = event => this.setState({ val: event.target.value });

  render() {
    return (
      <div>
        <h1>title</h1>
        <input value={this.state.val} onChange={this.changeVal} />
      </div>
    );
  }
}

const { shallow: setup } = setupComponent({
    component: InputComponent,
    elementsToFind: [
      {
        name: 'input',
        query: 'input'
      }
    ]
})

describe('Component', () => {
    it('updates values', () => {
        const { input, refresh } = setup();

        input.simulate('change', { target: { value: 'A new input value!' } });
        // By now the input variable is outdated and it's `props('value')` don't actual match the new value
        // It needs to be refreshed

        expect(refresh(input).props().value).toBe('A new input value!');
    });
});

Default Properties

If you want to add default properties to your component add an object to the SetupComponent function. Example:

import React, { Component } from 'react';
import { SetupComponent } from 'react-component-setup';

class DisplayName extends Component {
    render() {
        return (
            <h1>Hello {this.props.name}!</h1>
        );
    }
}

const { shallow: setup } = SetupComponent(
    component: DisplayName,
    defaultProps: { // the default props for the component
        name: 'Kyle'
    }
);

setup(); // returns element that is <h1>Hello, Kyle!</h1>

Note: default props will be overridden by props provided in the setup function call.

Enzyme shallow and mount options

To add TODO! If you want to add enzyme options to the shallow or mount command they can be provided similarly to default properties via the defaultEnzymeOptions.

Example:

import { SetupComponent } from 'react-component-setup';

const { shallow: setup } = SetupComponent(
    component: ComponentName,
    defaultEnzymeOptions: {
        context: {
            themecolor: '#fff'
        }
    }
);

To change the options on the fly provide a second argument to shallow/mount function.

import { SetupComponent } from 'react-component-setup';

const { shallow: setup } = SetupComponent(
    component: ComponentName,
    defaultEnzymeOptions: {
        context: {
            themecolor: '#fff'
        }
    }
);

setup({}, { context: { themecolor: '#different theme color' } )

Requirements:

  1. react version ^0.14.9 || ^15.0.0 || ^16.0.0
  2. react-dom version ^0.14.9 || ^15.0.0 || ^16.0.0
  3. enzyme version ~3.3.0

License

react-component-setup is MIT licensed.