How to test callback function with Jasmine

2019-08-20 16:43发布

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条回答
你好瞎i
2楼-- · 2019-08-20 17:36

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.

查看更多
登录 后发表回答