Created
October 13, 2018 18:13
-
-
Save JustinDFuller/1a69d16489b2665a56f5efa7a4f3bc65 to your computer and use it in GitHub Desktop.
Mocking and stubbing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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