How to test asynchronous function in Jasmine?

231 views
Skip to first unread message

aditya jain

unread,
Aug 4, 2017, 11:50:10 AM8/4/17
to Jasmine
Hi, I am using an asynchronous function in a class, which is below:

home.ts

//I am displaying only the function definition in the class I have used.

  click(){


   
function delayedAlert(message, time,cb){


             
return setTimeout( ()=> cb(message), time);
           
}


//function calling


delayedAlert
('xyz', 3000, (message)=> console.log(message));
     
       
}



In the spec.ts file I write the test code for the above function using TestBed.How to write the test using done ?

spec.ts

describe('Asynchronous call', () => {
let fixture: ComponentFixture<HomePage>;
let comp: HomePage;
let de: DebugElement;
let el: HTMLElement;
let message: string;


beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [HomePage],
imports: [
IonicModule.forRoot(HomePage),
],
providers: [NavController],
}).compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(HomePage);
comp = fixture.componentInstance;
de = fixture.debugElement;
});

it('test', function (done) {
//how to write the test using (done)??

})
})


Gregg Van Hove

unread,
Aug 4, 2017, 1:11:32 PM8/4/17
to jasmi...@googlegroups.com
There are two main ways that Jasmine gives you to test code that is asynchronous in nature.

1. Using the mock clock (https://jasmine.github.io/api/edge/Clock.html) (https://jasmine.github.io/edge/introduction#section-Jasmine_Clock)
2. Using the `done` callback (or Promises and `async` functions after 2.7)

Given your example code, I would recommend using the mock clock, which will let you manually `tick` to move the time forward in your test and have your callback be called without actually having to wait for 3 seconds during the test.

For an asynchronous function that is mostly about the side-effects it causes, in order to have your spec be truly async, you'd need to have it sort of wake up and check if the callback had been called yet, only calling `done` once that had successfully happened.

Hope this helps. Thanks for using Jasmine!

-Gregg

--
You received this message because you are subscribed to the Google Groups "Jasmine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jasmine-js+unsubscribe@googlegroups.com.
To post to this group, send email to jasmi...@googlegroups.com.
Visit this group at https://groups.google.com/group/jasmine-js.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages