[Unit testing + Jest] Use a Test Object Factory utils/generate

You can have a untils folder under root folder, to let jest include your files, you can do:

const path = require('path')

module.exports = {
  displayName: 'exercise',
  roots: [path.join(__dirname, '../src')],
  rootDir: path.join(__dirname, '..'),
  testEnvironment: 'node',
  testMatch: ['**/__tests__/*.exercise.*'],
  moduleDirectories: [
    'node_modules',
    __dirname,
    path.join(__dirname, '../src'),
  ],
  coverageDirectory: path.join(__dirname, '../coverage-exercises'),
  coveragePathIgnorePatterns: ['.*/__tests__/.*'],
  setupFilesAfterEnv: [require.resolve('./setup-env')],
  watchPlugins: [
    require.resolve('jest-watch-typeahead/filename'),
    require.resolve('jest-watch-typeahead/testname'),
  ],
}

SO that you can include those file at test:

import {buildNext, buildRes} from 'utils/generate'

 

Helper functions:

function buildReq({user = buildUser(), ...overrides} = {}) {
  const req = {user, body: {}, params: {}, ...overrides}
  return req
}

function buildRes(overrides = {}) {
  const res = {
    json: jest.fn(() => res).mockName('json'),
    status: jest.fn(() => res).mockName('status'),
    ...overrides,
  }
  return res
}

function buildNext(impl) {
  return jest.fn(impl).mockName('next')
}

 

Test example:

  test('if res.headersSent, then pass down error', () => {
    const res = buildRes({headersSent: true})
    const next = buildNext()
    const error = new Error('error')
    errorMiddleware(error, null, res, next)
    expect(next).toHaveBeenCalledWith(error)
    expect(next).toHaveBeenCalledTimes(1)
    expect(res.json).not.toHaveBeenCalled()
    expect(res.status).not.toHaveBeenCalled()
  })

 

posted @ 2021-08-09 15:42  Zhentiw  阅读(35)  评论(0编辑  收藏  举报