OMG! I ๐Ÿ’“ these tests ๐Ÿ˜

ยท

2 min read

I like writing tests but writing good tests is a skill - just like any other - that is best learnt by doing. So, here is a callout of the tests I have seen on the internet that inspired me to say

Wow, that's nice. I should do that.

And in no particular order -

1. Redux reducer tests with Jest

describe('todos reducer', () => {
  it('should handle ADD_TODO', () => {
    expect(
      reducer([], {
        type: types.ADD_TODO,
        text: 'Run the tests'
      })
    ).toEqual([
      {
        text: 'Run the tests',
        completed: false,
        id: 0
      }
    ]);
  });
});

Figure 1: Redux reducer test from redux documentation

At first glance this looks like a unit test but it also tests the reducer types. And when I want to expand the store I can easily use a test-driven approach by using expect.objectContaining instead of toEqual.

2. Express app integration tests with Supertest

describe('GET /user', function() {
  it('responds with json', function(done) {
    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });
});

Figure 2: Express integration test from Supertest documentation

These integration tests run quickly and make it possible to test routes, controllers and models all in one go. Although Express is the #1 NodeJS server framework, I prefer HapiJS but more on that in another post.

3. Mocking Axios with Jest

test('should fetch users', () => {
  const users = [{name: 'Bob'}];
  const resp = {data: users};
  axios.get.mockResolvedValue(resp);

  // or you could use the following depending on your use case:
  // axios.get.mockImplementation(() => Promise.resolve(resp))

  return Users.all().then(resp => expect(resp.data).toEqual(users));
});

Figure 3: Mock of axios from documentation Jest documentation

This little bit of wizadry turns slow integration tests into faster unit tests by removing the need for an API to respond. Of course mocks can be used for many things but this is my number #1 guy.

ย