Shaun Stone
Shaun Stone

Reputation: 21

'Express.js Async Handler' - Difficulty writing tests for it

I have this function I use to pass any failures directly to the express error handler. I am writing tests for it and I am trying to wrap my head around how I can test this properly by passing in the function correctly.

asyncHandlerUtil.js

const asyncHandlerUtil = fn => (req, res, next) => {
    return Promise
        .resolve(fn(req, res, next))
        .catch(next);
};

module.exports = asyncHandlerUtil;

Right now I have (Aware it's wrong atm)

asyncHandlerUtil.spec.js

import asyncHandlerUtil from './asyncHandlerUtil';

describe('Given the asyncHandlerUtil function', () => {
  describe('when is is called', () => {
    let middleware;
    let fn;
    let subFn;

    beforeEach(() => {
      subFn = jest.fn();
      fn = jest.fn(() => subFn);
      middleware = asyncHandlerUtil(fn);
      middleware();
    });
    it('should call fn', () => {
      expect(fn).toHaveBeenCalledWith(subFn);
    });
  // other tests needed for rejection and catching errors.
  });
});

Thanks!

Upvotes: 0

Views: 409

Answers (1)

Lin Du
Lin Du

Reputation: 102597

Here is the unit test solution:

asyncHandlerUtil.js:

const asyncHandlerUtil = (fn) => (req, res, next) => {
  return Promise.resolve(fn(req, res, next)).catch(next);
};

module.exports = asyncHandlerUtil;

asyncHandlerUtil.test.js:

const asyncHandlerUtil = require('./asyncHandlerUtil');

describe('62063369', () => {
  it('should pass', async () => {
    const mFn = jest.fn().mockResolvedValueOnce('mocked value');
    const mReq = {};
    const mRes = {};
    const mNext = jest.fn();
    const got = await asyncHandlerUtil(mFn)(mReq, mRes, mNext);
    expect(got).toBe('mocked value');
    expect(mFn).toBeCalledWith({}, {}, mNext);
  });
});

Unit test results with coverage report:

 PASS  stackoverflow/62063369/asyncHandlerUtil.test.js (12.14s)
  62063369
    ✓ should pass (5ms)

---------------------|---------|----------|---------|---------|-------------------
File                 | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------------|---------|----------|---------|---------|-------------------
All files            |     100 |      100 |     100 |     100 |                   
 asyncHandlerUtil.js |     100 |      100 |     100 |     100 |                   
---------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.218s

Upvotes: 3

Related Questions