1

I'd like to use assertions to check for invalid parameters in my private methods (and others that should only be called internally). I'd prefer:

  • A failed assertion terminates the program, or at least stops my automated tests. console.assert() doesn't appear to do this.
  • Assertions can be stripped out during production deployment (I'm using Grunt).
  • A very minimal solution (shouldn't need a library to do this).

EDIT: I'm not trying to test anything here. If my motivation for doing this is unclear, check out CC2 or Clean Code or the Wiki page: https://en.wikipedia.org/wiki/Assertion_(software_development)

4
  • 1. Why are you testing private methods? 2. Why would you put tests inside actual code? 3. Why not use a testing library? Feels like you're solving the wrong problem here. I bet your real problem is how to test your code properly given some situation you haven't mentioned. Commented Sep 5, 2015 at 4:13
  • this might be relevant to your concern philipwalton.com/articles/… Commented Sep 5, 2015 at 4:26
  • 2
    @JosephtheDreamer Assertions are not just for tests. They serve a complementary role to practices such as exception handling and logging, and are promoted in many programming books such as CC2. Commented Sep 5, 2015 at 6:13
  • @Daniel_L Thanks Daniel, but I'm not trying to test these methods. I'm looking to use assertions as "executable documentation" to catch developer mistakes within my code base. I have unit tests in place separately. Commented Sep 5, 2015 at 6:16

1 Answer 1

1

Something like?

const assert = env === "production"
    ? () => {}
    : (test, msg) =>  {
        if (!test) throw new Error(`assertion failed: ${msg}`);
      };

// ...

function foo(param) {
    assert(typeof param === "number", "param is a Number");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice, this meets all of my criteria! I'll accept, but bonus points if anyone can suggest a way to also drop the call statements during minification.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.