Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I verify a call to a stub which is configured to throw? #412

Closed
3 tasks done
benblank opened this issue Apr 16, 2019 · 1 comment
Closed
3 tasks done

How can I verify a call to a stub which is configured to throw? #412

benblank opened this issue Apr 16, 2019 · 1 comment

Comments

@benblank
Copy link

Description

I need to verify that a stub was called with a particular parameter, but also have that stub throw an error.

Issue

When a stub is configured to throw, attempting to verify it instead throws the configured error. (Also, my current attempt uses both .when and .verify on the same stub, which the docs suggest is incorrect anyway.)

Environment

  • node -v output: v10.8.0
  • npm -v (or yarn --version) output: 1.12.1
  • npm ls testdouble (or yarn list testdouble) version:
    yarn list v1.12.1
    warning Filtering by arguments is deprecated. Please use the pattern option instead.
    └─ testdouble@3.11.0
    ✨ Done in 0.56s.

Code-fenced Example

const assert = require('assert').strict;
const execa = require('execa');
const td = require('testdouble');

function subject() {
  try {
    const { stdout } = execa('foo');  // throws if "foo" doesn't exist or has a non-zero exit code
    const match = /some (.+) string/.exec(stdout);

    return match[1];
  } catch (ex) {
    // log it
  }

  try {
    const { stdout } = execa('bar');  // throws if "bar" doesn't exist or has a non-zero exit code
    const match = /a different (.+) string/.exec(stdout);

    return match[1];
  } catch (ex) {
    // log it

    return null;
  }
}

const stub = td.function(execa.sync);

td.replace(execa, 'sync', stub);
td.when(stub(), { ignoreExtraArgs: true }).thenThrow(new Error('command not found'));

assert(null === subject());

td.verify(stub('bar'), { ignoreExtraArgs: true });  // throws "command not found" error

How should I instead be configuring/verifying this stub?

@searls
Copy link
Member

searls commented Apr 17, 2019

This wouldn't be supported, as it falls under our advice not to verify what you stub. If the stubbing to throw an error is necessary, then an explicit verification would be redundant, as the stubbing would either be observable by the test directly (e.g. an error is thrown, as is the case here), or indirectly (the subject handles the error somehow and whatever it does next is asserted by the test).

For more commentary, see this FAQ

@searls searls closed this as completed Apr 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants