问题
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:
- a test for
myFunction
- 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