Jasmine 2.0 how to wait real time before running an expectation

后端 未结 2 801
甜味超标
甜味超标 2021-01-04 00:11

I am trying to test the postMessage API as there is a slight delay before message are receive i can not run expectation right after sending a message.

In jasmine 1.3

2条回答
  •  情话喂你
    2021-01-04 00:31

    Rather than waiting some number of milliseconds, jasmine has hooks to wait until a function returns. This page has some good example, and I've copied one here to show a specific way of testing ajax callbacks. Just add a spy as a callback to your function and wait for that callback to be executed.

    it("should make a real AJAX request", function () {
        var callback = jasmine.createSpy();
        makeAjaxCall(callback);
        waitsFor(function() {
            return callback.callCount > 0;
        }, "The Ajax call timed out.", 5000);
    
        runs(function() {
            expect(callback).toHaveBeenCalled();
        });
    });
    

    EDIT:

    Since you're testing that your application makes a specific callback, you can just replace that callback with a spy instead of creating a new one like I did.

    Jasmine 2.0 added a "done" style callback, so you should be able to do something like: (I haven't tested the syntax of this but hopefully a good start)

    it("should make an ajax callback with jasmine 2.0", function(done)) {
        // this is the object you are testing - assume it has the ajax method you want to call and the method that gets called when the ajax method is finished
        var myObject
        spyOn(myObject, "callback").andCallFake(function() {
            done();        
        });    
        myObject.makeAjaxCall();    
    }
    

提交回复
热议问题