React Testing

Practice (1)

Target

  • How to create test environment
  • How to test presentational pure component (without HOC component)
  • Test In unit
  • Integration test (with HOC component)
  • How to use cypress to do E2E test
  • jsdom
  • mocha
  • enzyme + enzyme-adapter
  • chai
  • sinon
  • ignore-styles (optional)

Packages

"test:unit": "mocha
--require @babel/register
--require ./client/test/helpers.js
--require ./client/test/dom.js
--require ignore-styles './client/test/src/**/*.spec.js'",

Run Test

"test:unit:watch": "npm run test:unit -- --watch"
npm run test:unit

File Structure

dom.js

helpers.js

describe('Test Component', () => {
  it('rule1', () => {
    // test code
  });

  it('rule2', () => {
    // test code
  });

  context('if in some condition', () => {
    it('rule3', () => {
      // test code
    });
  });
});

Getting started

mocha

.spec.js / .test.js

describe('hooks', function() {

  before(() => {
    // runs before all tests in this block
  });

  after(() => {
    // runs after all tests in this block
  });

  beforeEach(() => {
    // runs before each test in this block
  });

  afterEach(() => {
    // runs after each test in this block
  });

  // test cases
});

Hooks

mocha

Renderer

  • shallow
  • Only test in unit 
  • Run constructor, didMount,  didupdate, render
  • mount
  • Full DOM rendering 
  • Component that may interact with DOM APIs / wrapped in HOC 
  • render
  • Render react component to static HTML and analyze the resulting HTML structure 

enzyme

Assertion

  • expect

chai

// expect 1 === 1
expect(1).to.equal(1);
// expect object has key 'a'
expect({ a: 1 }).to.have.property('a');
// expect array have length of 3
expect([1, 2, 3]).to.have.lengthOf(3);
  •  Chainable getters

API doc: https://www.chaijs.com/api/bdd/

Demo

Test Practice

By Travor Lee

Test Practice

  • 128