I cannot test the reject for some reason. Here is the function and I want to test it 100%. now it is like 92% and complain about reject(e) is not tested..
public resolve(): Promise<{ [key: string]: boolean }> {
return new Promise<{ [key: string]: boolean }>(async (resolve, reject) => {
try {
for await (const setting of settings) {
// ObjectStore that acts like hashMap
this.store.set(setting.key, setting.value);
}
resolve();
}
catch (e) {
reject(e);
}
});
}
Updates:
I have to make another Mock to make the catch statement happening first. And TestBed.overrideProvider is not really working for me, so that I have to
it('should return a rejected promise', async() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
//inserting the new mock provider to trigger the catch
...
});
and then use the answer below (Thank you @Apoorva Chikara) and works for me
If there is easier way to accomplish this, please let me know
CodePudding user response:
You can catch the error and test it. It is similar to testing the resolving.
describe('Test Case', () => {
describe('Testing Sample 1', () => {
it('should return a rejected promise', () => {
service.resolve()
.catch((error) => {
expect(error).toEqual('the error string');
});
});
});
});
CodePudding user response:
Never pass an async function
as the executor to new Promise
! Your function should be simplified to
public async resolve(): Promise<{ [key: string]: boolean }> {
// ^^^^^
for await (const setting of settings) {
// ObjectStore that acts like hashMap
this.store.set(setting.key, setting.value);
}
}
and then you won't need a separate test for the code path that doesn't even exist. Furthermore, you probably don't want to use for await
, unless settings
is an asynchronous generator.