How to test an asynchronous function using karma/Jasmine in ionic2?

*爱你&永不变心* 提交于 2019-12-12 04:03:21

问题


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



来源:https://stackoverflow.com/questions/45311260/how-to-test-an-asynchronous-function-using-karma-jasmine-in-ionic2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!