I have a function for which i am trying to write a spec which is failing with the error
Unhandled promise rejection: [object Object]
Function:
someFunction(a,b,c) {
var dfd = q.defer();
this.getInfo(b,c).then((data)=> {
//do Something
dfd.resolve(data);
}).catch((error)=> {
dfd.reject(error)
})
return dfd.promise;
}
spec:
describe( 'SomeFunction', () => {
it( 'should reject when getInfo request fails', ( done ) => {
spyOn( utility, 'getInfo' ).and.callFake( async () => {
var deferred = q.defer();
deferred.reject( { error: 500 } );
return deferred.promise;
});
let promise = utility.someFunction( a,b,c );
expect(utility.getInfo).toHaveBeenCalled();
promise.then().catch( function ( data:any) {
expect( data ).toEqual( { error: 500 } );
} ).finally( done );
});
I want to write to here the test case for reject but then getting the error unhandled promise rejection.
Any one let me know if i am doing anything wrong here.
Any help would be appreciated.
You should use rejectWith(value):
Tell the spy to return a promise rejecting with the specified value when invoked.
to spy utility.getInfo() method. Since the return value of utility.someFunction is a promise, you should use expectAsync(actual) to create an asynchronous expectation.
index.ts:
import q from 'q';
const utility = {
someFunction(a, b, c) {
var dfd = q.defer();
this.getInfo(b, c)
.then((data) => {
dfd.resolve(data);
})
.catch((error) => {
dfd.reject(error);
});
return dfd.promise;
},
async getInfo(b, c) {
return 'real data';
},
};
export { utility };
index.test.ts:
import { utility } from './';
describe('69378465', () => {
it('should pass', async () => {
spyOn(utility, 'getInfo').and.rejectWith({ error: 500 });
await expectAsync(utility.someFunction('a', 'b', 'c')).toBeRejectedWith({ error: 500 });
expect(utility.getInfo).toHaveBeenCalled();
});
});
test result:
Test Suites & Specs:
1. 69378465
โ should pass (11ms)
>> Done!
Summary:
๐ Passed
Suites: 1 of 1
Specs: 1 of 1
Expects: 2 (0 failures)
Finished in 0.017 seconds