简体   繁体   中英

JasmineJS + AngularJS: How to mock the delay inside Spy#callFake()

Let's assume I have a service function that returns me the current location. And the function has callbacks to return the location. We can easily mock the function like as follows. But I wanted to introduce some delay (let's say 1 sec) before the callFake() invokes the successHandler(location).

Is there a way to achieve that?

xxxSpec.js

spyOn(LocationService, 'getLocation').and.callFake(function(successHandler, errorHandler) {

   //TODO: introduce some delay here

   const location = {...};
   successHandler(location); 
}

LocationService.js

function getLocation(successCallback, errorCallback) {
    let location = {...};
    successCallback(location);
}

Introducing delay in Javascript is easily done with the setTimeout API, details here . You haven't specified if you are using a framework such as Angular, so your code may differ slightly from what I have below.

It does not appear that you are using Observables or Promises for easier handling of asynchronous code. Jasmine 2 does have the 'done' callback that can be useful for this. Something like this could work:

it( "my test", function(done) {
    let successHandler = jasmine.createSpy();
    spyOn(LocationService, 'getLocation').and.callFake(function(successHandler, errorHandler) {
        setTimeout(function() {
            const location = {...};
            successHandler(location); 
        }, 1000); // wait for 1 second
    })

    // Now invoke the function under test
    functionUnderTest(/* location data */);

    // To test we have to wait until it's completed before expecting...
    setTimeout(function(){
        // check what you want to check in the test ...
        expect(successHandler).toHaveBeenCalled();
        // Let Jasmine know the test is done.
        done();
    }, 1500); // wait for longer than one second to test results
});

However, it is not clear to me why adding the timeouts would be valuable to your testing. :)

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM