p0lar_bear
p0lar_bear

Reputation: 2275

Pass a Jasmine spec on async timeout

Running Jasmine 2.8.

I've got a test case in which the failure case is an event handler being triggered under a condition when it should not be. Note that the codebase that provides events here is part of a proprietary, developed-in-house system and as such these are not DOM events and I am not leveraging any popular JS frameworks:

    it('should trigger the event handler in state 0', function (done) {
        function specCb(ev) {
            expect(ev).toBeDefined();
            expect(ev.data).toBe('some value');
            done();
        }
        thing.state = 0;
        simulateEventTrigger(thing, specCb);
    });

    it('should not trigger the event handler in state 1', function (done) {
        function specCb(ev) {
            done.fail('this should not be called in state 1');
        }
        thing.state = 1;
        simulateEventTrigger(thing, specCb);
    });

The second spec will always fail because either the callback is called, which explicitly fails the spec, or the spec times out waiting for done() to be called, thus failing it. How do I get Jasmine to pass a spec if it times out?

Upvotes: 0

Views: 439

Answers (2)

Antonio Narkevich
Antonio Narkevich

Reputation: 4326

Actually it function accepts the callback so you could do something like this:

const TEST_TIMEOUT = 1000;
const CONSIDER_PASSED_AFTER = 500;

describe('a test that is being considered passing in case of a timeout', () => {
    it('should succeed in after a specified time interval', done => {
        setTimeout(() => {
            done();
        }, CONSIDER_PASSED_AFTER);
    }, TEST_TIMEOUT);
});

Upvotes: 1

Charlie Martin
Charlie Martin

Reputation: 8406

Check out spies in Jasmine. Spies allow you to "spy on" a function and assert whether it has been called and with which arguments. Or, in your case, whether it has not been called. An example might look like this...

describe("A spy", function() {
  var evHandlers;

  beforeEach(function() {
    evHandlers = {
       callback: function (e) {}
    }

    spyOn(evHandlers, 'callback');
  });

  it('should not trigger the event handler in state 1', function (done) {
      thing.state = 1;
      simulateEventTrigger(thing, evHandlers.callback);
      expect(evHandlers.callback).not.toHaveBeenCalled();
  });
});

Upvotes: 1

Related Questions