athomasoriginal / demo-clojurescript-jest

ClojureScript and Jest
7 stars 2 forks source link

DEMO ClojureScript + Jest

Jest and CLJS. I always wondered why I never saw anyone using Jest with CLJS. As ClojureScript developers we lean heavily on React and the React ecosystem. Why not Jest?

Quickstart

TODO

Issues

Breakdown

The following are setup steps that I included in the event someone wants to see how I came to the current implementation. You don't need to run through these yourself, its mostly as a reminder for myself.

Basic Jest Setup

Getting Started

If we start with the getting started section of Jest start by converting the Jest test to CLJS:

Before we can run jest against our tests, we have to compile our clojurescript. To make things easier we will use figwheel.main

Multiple Tests

In the getting started section we only had one file with tests. This means that our yarn test command was simple. We just told it to run the one file we had. However, as your project scales you are going to want to tell it how to run more than just one file. This section will explain how to scale to more than one file in the same dir. So lets update our package.json npm test script to look like this:

jest --verbose target/public/cljs-out/test/demo/*

Snapshot Testing

In order to reproduce the minimal react snapshot test as outlined in the Jest documentation you need to perform the following setup:

  1. Install test dependencies
  2. Setup webpack externs bundle

Step 1 Install Test Dependencies

Step 2 Setup webpack externs bundle

Step 3 Write your react component test

The javascript version of Jest's example snapshot test looks like this:

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();
});

Convert the above into ClojureScript:

(ns demo.component-test
  (:require [demo.component :as component]
            [reagent.core :as r]
            [renderer]))

(js/it
  "Render correctly"
  (fn []
    (let [button [component/button
                  {:class "test-class"
                   :type  "button"}]
            tree   (.. renderer (create (r/as-element button)) (toJSON))]
        (.. (js/expect tree) (toMatchSnapshot)))))

And now we can run our tests

yarn test

Gotchas

This section is going to review a bunch of the problems I faced when working through the above:

When to use Jest

I would lean on Jest for front end specific testing

Resources