Skip to content

Instantly share code, notes, and snippets.

@JustinDFuller
Created October 13, 2018 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinDFuller/1a69d16489b2665a56f5efa7a4f3bc65 to your computer and use it in GitHub Desktop.
Save JustinDFuller/1a69d16489b2665a56f5efa7a4f3bc65 to your computer and use it in GitHub Desktop.
Mocking and stubbing
/* This is my file I'll be testing foo.js */
import fs from 'fs'
import { promisify } from 'util'
const readFileAsync = promisify(fs.readFile)
export function readJsonFile (filePath) {
return readFileAsync(filePath).then(JSON.parse)
}
/* This is my test file foo.test.js */
import fs from 'fs'
import test from 'ava';
import { stub } from 'sinon'
import proxyquire from 'proxyquire'
test('readJsonFile with proxyquire', async function (t) {
t.plan(2)
/* fs.readFile is overwritten for this import of foo.js */
const { readJsonFile } = proxyquire('./foo.js', {
fs: {
readFile(filePath, callback) {
t.is(filePath, 'myTestFile')
return callback(null, '{ success: true }')
}
}
})
const results = await readJsonFile('myTestFile')
t.deepEqual(results, { success: true })
})
test('readJsonFile with sinon', async function (t) {
t.plan(1)
/* fs.readFile is overwritten everywhere */
const fsStub = stub(fs, 'readFile')
.withArgs('myTestFile')
.callsArg(2, null, '{ success: true }')
const results = await readJsonFile('myTestFile')
t.deepEqual(results, { success: true })
// Won't happen if test fails :(
fsStub.restore()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment