How to test a function which calls async function using Jasmine

how to test async function jasmine
jasmine async/await
angular unit test async/await
jasmine expectasync
jasmine spyon
jasmine test promise reject
jasmine mock promise
angular unit test ngoninit

How to test this function:

var self = this;
self.someVariable = "initial value";
self.test = function() {
   self.functionWhichReturnsPromise().then(function() {
     self.someVariable = "new value";
   });
}

I have test case like below, I know it is wrong because before promise is resolved, the assert statement will be executed by jasmine:

it("should test the function test", function (done) {
    var abc = new ABC();
    abc.test();
    expect(abc.someVariable).toBe('new value');
});

Note that I do not want to use setTimeout() or any sleep methods.


Two things, you need your test function to return the Promise and you need to use an arrow function or .bind the callback to the parent function (otherwise the this in this.someVariable will refer to the callback function):

this.test = function() {
   return this.functionWhichReturnsPromise().then(() => {
     this.someVariable = "new value";
   });
}

or

this.test = function() {
   return this.functionWhichReturnsPromise().then(function() {
     this.someVariable = "new value";
   }.bind(this));
}

Then in your test you can do:

it("should test the function test", function (done) {
    var abc = new ABC();
    abc.test().then(function() {
       expect(abc.someVariable).toBe('new value');
       done();
    });
});

Asynchronous work, Methods usually have dependencies on other methods, and you might get into a situation where you test different function calls within that one� Unit Testing Async Calls and Promises with Jasmine. get into a situation where you test different function calls within that one method. on the spied on function in .then of the async call.


You can just spy on the function which returns the promise.

describe('when test method', function() {
  beforeEach(function() {
    this.promiseResult = Math.random();
    spyOn(ABC.prototype, 'functionWhichReturnsPromise')
      .and.returnValue(Promise.resolve(this.promiseResult));
  })

  it('then should change someVariable with the result of functionWhichReturnsPromise', function() {
    var abc = new ABC();
    abc.test();
    expect(abc.someVariable).toBe(this.promiseResult);
  });
});

No need to wait the promise, inside this unit test, you are not interested in how functionWhichReturnsPromise actually works, you only want to see that the result of calling functionWhichReturnsPromise will update someVariable value.

Have fun and luck

Unit Testing Async Calls and Promises with Jasmine, Code under test var MyApp = function () { var testAsync = function spy on async calls and use helpers to mock success/failure", function� The nice thing about using async/await inside Jasmine is that a try/catch already surrounds each test so that the framework can tally all the errors in the suite rather than crashing to a halt the


Now async and await are available in jasmine. you can use them to test your async function weather its a promise or observable.

it("should test the function test", async (done) => {
    var abc = new ABC();
    abc.test();
    expect( await abc.someVariable).toBe('new value');  // await will wait until abc.someVariable resolved or rejected
});

I have been using async and await in my angular 4 application test and it should work for you.

Testing Asynchronous Code • Angular, The fetch() function returns a promise, so we would normally chain a then() call, passing a function to be called when the promise resolves,� Calls to run() methods act as individual testing blocks, the last of which would make the asynchronous call. In the simplest case, a setTimeout() can be used to simulate asynchronous behavior. In a more complex usage, an actual call would be made, such as to an Ajax-enabled object. The waitsFor() method accepts three arguments: a "latch" function


I've written two samples to show how to wait for the promise inside the test function. JavaScript: https://codepen.io/zhangyanwei/pen/rNNXKaV

function trackPromise() {
  const P = Promise;
  Promise = function() {
    const p = new P(...arguments);
    Object.assign(this, p);
    Promise.recent = p;
  };
  Object.assign(Promise, P);
}

TypeScript: https://codepen.io/zhangyanwei/pen/ZEEgNNB

// Mixin interface, you could put it into *.d.ts file.
interface PromiseConstructor {
    recent: Promise<unknown>;
}

function trackPromise() {
  // Only overwrite the constructor
  const P = Promise;
  Promise = function<T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T> {
      const p = new P(executor);
      Promise.recent = p;
      return p;
  } as unknown as PromiseConstructor;
}

Mocking calls with Jasmine, Hi, how can I use async/await with Jasmine? Is this supported somehow? I'd like to do it('should run test', async function()� Still, that’s already pretty slick. You couldn’t ask for more readable code inside this function. Now let’s try that in a test. The nice thing about using async/await inside Jasmine is that a try/catch already surrounds each test, so that the framework can tally all the errors in the suite rather than crashing to a halt the first time it


Unit Testing with Jasmine and Async/Await, This spec will not start until the done function is called in the call to async execution of test preparation and expectations", function(done)� If the function passed to Jasmine takes an argument (traditionally called done), Jasmine will pass a function to be invoked when asynchronous work has been completed. It’s vital that the done callback be called exactly once, and that calling done be the last thing done by the asynchronous function or any of the functions that it calls.


How to use async/await with Jasmine? � Issue #923 � jasmine , You can use it to mock an asynchronous method, check it has been called, and then resolve it inside your spec. Copy. it('generates some token', async () => { let � With Jasmine async testing, we have to call the async code in the beforeEach() function that runs before each it() function block within a describe() function block. We also have to let Jasmine know when the async function has completed by calling the special done() callback function Jasmine provides.


Jasmine with Async/Await � GitHub, In our component, we want to fetch the users by calling the getUsers() each provider's method into a Jasmine spy automatically (i.e. jasmine.createSpy() ). Lastly, we create an it block and wrap it with the fakeAsync function. A suite groups a set of specs or test cases. It’s used to test a specific behavior of the JavaScript code that’s usually encapsulated by an object/class or a function. It’s created using the Jasmine global function describe() that takes two parameters, the title of the test suite and a function that implements the actual code of the test