Skip to content

Instantly share code, notes, and snippets.

@vimyum
Created December 15, 2017 16:02
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 vimyum/84493cdcd762f5cc909f2b38003e8190 to your computer and use it in GitHub Desktop.
Save vimyum/84493cdcd762f5cc909f2b38003e8190 to your computer and use it in GitHub Desktop.
Jestサンプルのテスト対象
// (1): モックを定義 (1)
const mockFileData = `test\n is\n spec.`;
jest.mock('fs', () => {
return {
readFileSync: jest.fn(() => mockFileData),
readFile: jest.fn((path, opt, cb) => {
cb(null, mockFileData);
});
};
});
// (2): 検証用((4),(5))にモック読み込む
import * as fs from 'fs';
// (3): (1)を利用するモジュールを読み込む
import {LineCount, LineCountAsync, LineCountDiff} from './app';
describe('test', () => {
beforeEach(() => {
fs.readFileSync.mockClear();
});
const path = 'dummy';
it('LineCount()', () => {
const result = LineCount(path);
expect(result).toBe(3);
expect(fs.readFileSync.mock.calls.length).toBe(1); // (4): モックが呼ばれたか検証
expect(fs.readFileSync.mock.calls[0][0]).toBe(path); // (5): モックが呼ばれた際の引数を検証
});
it('LineCountAsync', () => {
return LineCountAsync(path).then(result => {
expect(result).toBe(3);
});
});
it('LineCount() // ファイルが空', () => {
fs.readFileSync.mockImplementation(() => ''); // 空文字を返す振る舞いを定義
const result = LineCount(path);
expect(result).toBe(1); // テストに失敗します。
});
it('LineCount() // ファイルが空でない', () => {
fs.readFileSync.mockImplementation(() => 'hello'); // 文字列を返す振る舞いを定義
const result = LineCount(path);
expect(result).toBe(1);
});
it('LineCountDiff()', () => {
const path2 = 'dummy2';
const generator = function* (e) { yield *e; };
const mockFn = generator(['1\n2\n3', '1']);
fs.readFileSync.mockImplementation(() => mockFn.next().value);
const result = LineCountDiff(path, path2);
expect(result).toBe(2);
});
});
import {promisify} from 'util';
import * as fs from 'fs';
const readFilePromise = promisify(fs.readFile);
export function LineCount (path: string): number {
const data = fs.readFileSync(path, 'utf8');
return data.split('\n').length;
}
export async function LineCountAsync (path: string): Promise<number> {
const data = await readFilePromise(path, 'utf8');
return data.split('\n').length;
}
export function LineCountDiff (path1: string, path2: string): number {
const data1 = fs.readFileSync(path1, 'utf8');
const data2 = fs.readFileSync(path2, 'utf8');
return data1.split('\n').length - data2.split('\n').length;
}
export default { LineCount, LineCountAsync, LineCountDiff };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment