How to test an asynchronous function using karma/J

2019-08-19 02:02发布

问题:

Below I have written down the code in which there is an asynchronous function, that uses setTimeout() internally and prints message after 3seconds.

I have to write the spec using Jasmine.

I have followed the docs but I didn't get how to apply this in the code.

home.ts

//implementing only function written in a class.All imports are done properly.

click(){

function delayedAlert(message: string, time: number, cb) {
      return setTimeout(() => cb(message), time);
    }
    delayedAlert('Aditya3', 3000, (message) => console.log(message));//function is called
  }
}

home.spec.ts

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


    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('Asynchronous testing with callback', ()=>{
         //how to write the spec here for the asynchronous function wrriten in the above class using Karma/Jasmine.
})
});

In the comments marked in the test spec, I need to write the spec.

回答1:

Use the done() method. Check this out.

http://www.htmlgoodies.com/html5/javascript/using-the-done-method-in-your-jasmine-driven-asynchronous-javascript-tests.html