jeudi 21 février 2019

Mock shell command output in Jest

I'm writing a cli tool and I'm trying to write tests for it in Jest. I have some functions that call out to git, but I need to mock the returns from those calls or they aren't going to be consistent.

The code I'm using to call out to the shell looks like this.

import { exec } from "child_process";

function execute(command) {
  return new Promise((resolve, reject) => {
    exec(command, resolve);
  });
}

export const getGitDiff = function () {
  return execute("git diff")
};

How can I write a test for that in Jest?

What I tried was

import { getGitDiff } from './getGitDiff';

describe('get git diff', () => {
  it('should send "git diff" to stdin', () => {
    const spy = jest.spyOn(process.stdin, 'write');
    return getGitDiff().then(() => {
      expect(spy).toHaveBeenCalled();
    })
  });
});

Aucun commentaire:

Enregistrer un commentaire