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

Comments

@lazarljubenovic
Copy link

commented Mar 11, 2017

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

@mirisuzanne

This comment has been minimized.

Copy link
Member

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

This comment has been minimized.

Copy link
Author

commented Mar 11, 2017

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
Projects
None yet
2 participants
You can’t perform that action at this time.