How to test callback function with Jasmine

天大地大妈咪最大 提交于 2019-12-11 17:32:40

问题


Given the function with callback as follows:

myfunction('some value', function(){
    //do something...
})

How can I cover and test it using Jasmine ? It never enters in the flow inside the function(){... callback.

Thanks


回答1:


In cases like this, there are (at least) two unit tests that you need to create:

  1. a test for myFunction
  2. a test for the callback

So it might look something like this:

it('should test myFunction', () => {
  let spy = jasmine.createSpy();
  let result = myFunction(spy);
  expect(spy).toHaveBeenCalledWith(...args);
  expect(result).toBeCorrectOrSomething();
});

it('should test the callback', () => {
  let callback = createCallback();
  let result = callback(...args);
  expect(result).toBeCorrectOrSomething();
});

Note that I say at least 2 tests because you will probably need to test different paths through each of these functions.

Also note that this requires you to be able to access the callback in your tests, so it needs to be exposed from the module you are creating.



来源:https://stackoverflow.com/questions/50706943/how-to-test-callback-function-with-jasmine

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