Git Product home page Git Product logo

stub-spawn-once's Introduction

stub-spawn-once

Stubs child_process.spawn for a single command; cleans up afterwards. Perfect for testing.

NPM

Build status semantic-release js-standard-style

Read Node mocking examples and mocked-env

Why

Mocking child_process.spawn is hard. See for yourself - the stubbing api for your tests is hard in mock-spawn or spawn-mock. I wanted something much simpler: just specify exit code and stdout and stderr for a single execution. This module does this

const execa = require('execa') // or any module
const { stubSpawnOnce } = require('.')
stubSpawnOnce(
  '/bin/sh -c echo "hello"',
  0, // exit code
  'hi from stub!', // stdout
  'and some error output' // stderr
)
execa
  .shell('echo "hello"')
  .then(console.log)
  /*
    output:
    {
      stdout: 'hi from stub!',
      stderr: 'and some error output',
      code: 0,
      failed: false,
      killed: false,
      signal: null,
      cmd: '/bin/sh -c echo "hello"',
      timedOut: false
    }
  */
  .then(() => {
    // call command again - the stub is gone
    return execa.shell('echo "hello"')
  })
  .then(console.log)
  /*
    output:
    {
      stdout: 'hello',
      stderr: '',
      code: 0,
      failed: false,
      killed: false,
      signal: null,
      cmd: '/bin/sh -c echo "hello"',
      timedOut: false
    }
  */

*hint exit code argument is optional and you can omit it (then 0 will be returned)

const { stubSpawnShellOnce } = require('.')
stubSpawnShellOnce('my command', 'hi there', 'error output string')

Install

Requires Node version 6 or above.

npm install --save-dev stub-spawn-once

Use

Examples from Mocha unit tests. Common information

  • only the given command is stubbed, other spawn commands are unaffected by the stub.
  • a stub will be removed after it runs once.

stubSpawnOnce

const { stubSpawnOnce } = require('stub-spawn-once')
const execa = require('execa')
it('prints mock output', () => {
  const cmd = 'echo "hello"'
  // output "foo" instead of "hello"
  stubSpawnOnce(`/bin/sh -c ${cmd}`, 0, 'foo', 'bar')
  return execa.shell(cmd)
    .then(result => {
      // result.code = 0
      // result.stdout = "foo"
      // result.stderr = "bar"
    })
})

stubSpawnShellOnce

const { stubSpawnShellOnce } = require('stub-spawn-once')
const execa = require('execa')
it('prints mock output', () => {
  const cmd = 'echo "hello"'
  // output "foo" instead of "hello"
  stubSpawnShellOnce(cmd, 0, 'foo', 'bar')
  return execa.shell(cmd)
    .then(result => {
      // result.code = 0
      // result.stdout = "foo"
      // result.stderr = "bar"
    })
})

Bonus

As a bonus, this module also mocks child_process.execFile allowing you easy testing.

const {stubSpawnOnce} = require('stub-spawn-once')
stubSpawnOnce('echo "hello"', null, 'foo', 'bar')
const cp = require('child_process')
cp.exec('echo "hello"', (code, out, errors) => {
  // code is null
  // out is "foo"
  // errors is "bar"
})

You can use alias stubExecOnce to stubSpawnOnce

const {stubExecOnce} = require('stub-spawn-once')
stubExecOnce('echo "hi"', "bye")

You can pass desired error instance

const error = new Error('my error')
stubExecOnce('invalid command', error)
cp.exec('invalid command', err => {
  // err === error
})

Small print

Author: Gleb Bahmutov <[email protected]> © 2017

License: MIT - do anything with the code, but don't blame me if it does not work.

Support: if you find any problems with this module, email / tweet / open issue on Github

MIT License

Copyright (c) 2017 Gleb Bahmutov <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

stub-spawn-once's People

Contributors

bahmutov avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

stub-spawn-once's Issues

Consider exporting `stubSpawnOnce` as default

Hey, nice lib!

Currently you only use named exports (in ES6 paradigm). It complicates things and make your API surface unclear imho.

You could export by default stubSpawnOnce as it seems to be the most common use case.
And export 2 named exports:

  • stubExec as stubSpawnOnce.
  • stubSpawn as stubSpawnShellOnce.

This makes things simpler and let the user name the default import however he wants. You get a clearer API and it covers every style of importing stuff. Plus you don't have to manage aliases.

// basic
import stubExec from 'stub-spawn-once'

// mixed
import stubExec, { stubSpawn } from ' stub-spawn-once'

// namespaced
import stubs from 'stub-spawn-once'
stubs.stubExec()
stubs.stubSpawn()

Return a promise

To allow stubbing multiple calls in the right sequence, return a promise when a stub has been used. For example

beforeEach(() => {
      // first tries to get semantic commits
      // then tries to get all commits
      stubExecOnce('git log --pretty=full', logPretty)
      // stub same call again!
      .then(() => stubExecOnce('git log --pretty=full', logPretty))
})

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.