Justin Warner
Justin Warner

Reputation: 879

Verify unit tests are actually being ran, not just skipped over because it's poorly written

We're using sinon and mocha to do our unit tests. I've come up with the problem several times where I write some tests (Maybe in a promise, or a callback, or a stub) and the tests in these do not ever get hit, thus they aren't actually testing anything.

I can't imagine being the only one who has done this, so was wondering what people do to verify the test they wrote is actually being ran.

As an example:

// sStuff...

let myStub = sinon.stub(className, "classMethod", (result) => {
    // THIS will never be ran.
    expect(result).to.be.equal(5);
});

expect(myStub.callCount).to.be.equal(0);

// Stuff...

The test won't complain it wasn't ran, because we have the callCount check, but in reality, we're never calling something on className to have the classMethod function to be called and testing the result against 5.

Any common solutions? I couldn't think of search terms for this.

Thanks!

Upvotes: 2

Views: 54

Answers (1)

forsvarir
forsvarir

Reputation: 10839

I've never used sinon or mocha. That said, the easiest approach to validate that a test does what you're expecting it to is make sure it fails if its conditions aren't met.

In TDD, you'd follow the Red, Green, Refactor cycle which helps you to avoid this problem because you always experience the test failing and then being 'fixed' by the new code that you implement.

If I have to write tests for existing code, then I will typically write the test I feel is needed (which would pass), then change the behaviour of the code to validate that it 'breaks the test'. If it doesn't break the test, then the test isn't any good so I go back and fix the test. I then rollback the change to the code and validate that the test passes again.

Validating that the tests can fail takes a little longer than just writing them to pass, however the fail cycle helps to confirm that the tests are actually worthwhile and working as expected.

Upvotes: 2

Related Questions