isValidWord.ts
import {readFile} from 'fs/promises'; // we're going to mock this
export async function isValidWord(word: string) {
const validWords = await getValidWords();
return validWords.indexOf(word) !== -1;
}
async function getValidWords() {
const contents = await readFile('./dict.txt', 'utf-8');
return contents.split('\n');
}
isValidWord.spec.ts
import {test} from 'hoare';
import {mock} from 'cjs-mock';
import * as mod from './isValidWord'; // just used for type
const dict = ['dog', 'cat', 'fish'].join('\n');
const mockMod: typeof mod = mock('./isValidWord', {
'fs/promises': {readFile: () => Promise.resolve(dict)},
});
test('valid word returns true', async (assert) => {
const result = await mockMod.isValidWord('dog');
assert.equal(result, true);
});
isValidWord.js
const {readFile} = require('fs/promises'); // we're going to mock this
export async function isValidWord(word) {
const validWords = await getValidWords();
return validWords.indexOf(word) !== -1;
}
async function getValidWords() {
const contents = await readFile('./dict.txt', 'utf-8');
return contents.split('\n');
}
isValidWord.spec.js
const {test} = require('hoare');
const {mock} = require('cjs-mock');
const dict = ['dog', 'cat', 'fish'].join('\n');
const mockMod = mock('./isValidWord', {
'fs/promises': {readFile: () => Promise.resolve(dict)},
});
test('valid word returns true', async (assert) => {
const result = await mockMod.isValidWord('dog');
assert.equal(result, true);
});
/fake/a/foo.js
const bar = require('./bar');
module.exports = function() {
return 'foo ' + bar();
}
/fake/b/example.js
const mockedFoo = mock('../a/foo', { //relative to example.js
'./bar': () => 'fakeBar', //relative to foo.js
});