Testing an extension to expect.js

94 views Asked by At

I'm writing some expect.js matchers and I'd like to test the matchers themselves. So I want to write positive and negative tests. Let's say I've written

toContainItem(name);

used like this;

expect(femaleNames).toContainItem('Brad'); // test fails
expect(femaleNames).toContainItem('Angelina'); // test passes

What I want to do is write a test for the negative case, like so;

 it('should fail if the item is not in the list', function() {
     expect(function() {
         expect(femaleNames).toContainItem('Brad'); 
     }).toFailTest('Could not find "Brad" in the array');
 });

I'm not sure how to run my failing test code in an environment where it doesn't fail the containing test. Is this possible?


EDIT: Based on Carl Manaster's answer, I've come up with an extension to expect, allowing the code above to work;

expect.extend({
    toFailTest(msg) {
        let failed = false;
        let actualMessage = "";
        try
        {
            this.actual();
        } 
        catch(ex)
        {
            actualMessage = ex.message;
            failed = true;
        }

        expect.assert(failed, 'function should have failed exception');

        if(msg) {
            expect.assert(actualMessage === msg, `failed test: expected "${msg}" but was "${actualMessage}"`);
        }
    }
});
1

There are 1 answers

2
Carl Manaster On BEST ANSWER

I would think you could wrap the inner expect in a try/catch block, where you clear a failure variable in the catch clause, then make your actual assertion about the value of the variable.

let failed = true;
try {
  expect(femaleNames).toContainItem('Brad');
} catch (e) {
  failed = false;
}
expected(failed).toBe(false);