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

Test if a function throws? #92

Closed
lazarljubenovic opened this issue Mar 11, 2017 · 2 comments
Closed

Test if a function throws? #92

lazarljubenovic opened this issue Mar 11, 2017 · 2 comments

Comments

@lazarljubenovic
Copy link

It would be really nice to add ability to test if a function throws (like expect(...).toThrow('error message').

@mirisuzanne
Copy link
Member

mirisuzanne commented Mar 11, 2017

I agree. Here's how we did it in Susy. I don't feel like I can ship that as part of True, because it adds a function to your production code. I don't want True to be a production dependency, so it's better if that function lives outside True.

Add a variable and function like these to your project:

$_test-environment: false;

@function _error(
  $message,
  $capture: $_test-environment
) {
  @if $capture {
    @return 'ERROR: #{$message}';
  }

  @error '#{$message}';
}

Return that function wherever you would normally @error:

// what you had before...
@error "that won't work at all, please try again";

// what you use now...
@return _error("that won't work at all, please try again");

In your production code, set $_test-environment: false; and then change it to true in your testing environment. Suddenly failing functions will return error messages you can test for:

  @include test('Error on invalid thing') {
    @include assert-equal(
      my-function(3),
      "ERROR: that won't work at all, please try again"
    );
  }

Does that make sense? If you have ideas for a better way to do that without adding production requirements, I'm all ears!

@lazarljubenovic
Copy link
Author

Aaah, this is one of those tricks that are so obvious once someone tells you about them. Yeah, it makes perfect sense. Thanks for sharing the idea!

It's indeed tricky to do anything similar without adding a production dep 😐 If I experience some kind of sudden enlightenment, I'll make sure to drop by with an idea or two 😄

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