Testing in JS

JS features

  • Free functions
  • Classes (since ES6)

A lot of "logic" in JS apps happens in free functions

  • Redux actions
  • Redux reducer
  • Selectors
  • API calls
  • Composition
function add(x, y) {
	return x + y
}

describe("math", function () {
	
	it("should add two numbers", function() {

		let result = add(3, 4)

		expect(result).toBe(7)
	})

})

How to test UI?

Option 1

Automate the UI

Selenium or smth similar

  • Actually fills in values in the UI
  • Clicks buttons
  • Selects elements based on CSS
  • Very slow
  • Very flaky

Option 2

Use React (or smth similar)

Why React?

  • V = f(D)
  • Functions can be unit tested

JEST

  • Snapshot testing
  • Don't write assertions yourself
  • Protect against unintended changes
import React from 'react';
import Link from '../Link.react';
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  const tree = renderer
    .create(<Link page="http://www.facebook.com">Facebook</Link>)
    .toJSON();
  expect(tree).toMatchSnapshot();
});
exports[`renders correctly 1`] = `
<a
  className="normal"
  href="http://www.facebook.com"
  onMouseEnter={[Function]}
  onMouseLeave={[Function]}
>
  Facebook
</a>
`;

Testing in JS

By Thomas Eizinger

Testing in JS

  • 612