2.0.0 • Published 7 years ago

mock-path-with-spy-that-returns-x v2.0.0

Weekly downloads
3
License
ISC
Repository
github
Last release
7 years ago

Build Status Standard - JavaScript Style Guide

mock-path-with-spy-that-returns-x

Mocks a given path with a spy that returns either a symbol or something provided by you.

Why?

Because in unit tests, we mock some dependency functions.
And, usually, we like them to return a constant value.
And, usually, we like to assert their calls/args.
And, usually, we require the test subject multiple times.

This utility fits that pattern.

How?

Example

dep.js

// we will be mocking this file

module.exports = (x) => x.toUpperCase()

index.js

// this module will be our test subject

const dep = require('./dep')
module.exports = (x) => dep(x) + '-foo'

index.test.js

// unit tests here

const assert = require('assert')
const mockPathWithSpy = require('mock-path-with-spy-that-returns-x')
const requireUncached = require('require-uncached')

// set up a mock
const depMocks = mockPathWithSpy(
  './dep', // path to mock
  'MOCKED' // mocked function return value
)

// test A
const depMockA = depMocks.next().value // mock
const subjectA = requireUncached('.')
const actualA = subjectA('a')
assert.strictEqual(actualA, 'MOCKED-foo') // `./dep` is mocked
assert.deepStrictEqual(depMockA.spy.args, [['a']]) // spy available

// test B
const depMockB = depMocks.next().value
const subjectB = requireUncached('.')
const actualB = subject('b')
assert.strictEqual((actualB, 'MOCKED-foo')
assert.deepStrictEqual(depMockB.spy.args, [['b']])

API

mockPathWithSpy(path[, constantReturn]) (generator)

  • path
    The path to mock. Will be passed to mock.
  • constantReturn (optional)
    If provided, the spy will return provided value.
    If not provided, the spy will return a symbol that is unique to each mock.
    The description of the symbols will be path.

Returns an iterator:
On next, the path is mocked with a new spy and an object is returned:

Caveats

Uses module.parent

So it must always be required directly in the module where it is used. This may be fixed by using caller-path instead of module.parent, so please report an issue if you find that it bothers you.

requires the mocked module

The path is required and the exported function’s length is examined, for the purpose of the mock function being of the same arity as the mocked function.