Hack: Quickly Verify That All Your Mocha/Chai Tests Have Valid Assertions

Chai is a popular Node/browser assertion library. However - as everything - it has its flaws. An important flaw is that it performs checks on property access - and if you e.g. misspell the name of an assertion, it will be just ignored (for there is no way for Chai to know that you tried to access a non-existent property). This may be fixed in the future with ES6 proxies but so far you risk having tests that actually do not test anything. Though you should of course always develop your tests so that they initially fail and thus you know they actually assert something :-).

Anyway, there is a neat quick way to verify that all your tests have at least one valid assertion - simply replace expect with expect.not.

If you use Mocha and its mocha.opts to have a single file (common.js in my case) that imports Chai and exposes it to all tests then you have a single place do do this:

// file: test/mocha.opts
--require test/common
// file: test/common.js
// Before: global.expect = require("chai").expect;
var expect = require("chai").expect;
global.expect = function(target) {
    return expect(target).not;

When this change is in place, you expect all your tests to fail. If any one is passing then it has no valid assertions.


Tags: JavaScript

Copyright © 2024 Jakub Holý
Powered by Cryogen
Theme by KingMob