jmcdo29 / jmcdo29/testing-nestjs
[NEW TEST] Testing for interceptor failure
- Dominant language
- TypeScript
- Stars
- 3k
- Forks
- 375
- PR merge metrics
- No merged PRs in 30d
Description
### Is there an existing issue for this?
- [X] I have searched the existing issues
### Feature Test To Be Requested
I was using your CatInterceptor test as a template for a request interceptor test.
It was not clear how to test for an expected failure. Below is sketch of the test I created:
```typescript
class FailingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable {
throw new Error();
}
}
const interceptor = new FailingInterceptor();
// create the mock CallHandler for the interceptor
const next = {
handle: () => EMPTY,
};
it('should fail', () => {
const ctxMock = createMock({
switchToHttp: () => ({
getRequest: () => ({
headers: {},
}),
}),
});
expect(() =>
interceptor
.intercept(ctxMock, next)
.subscribe({ complete: () => fail() }),
).toThrowError(Error);
expect(fnAfterFailure).not.toHaveBeenCalled();
});
```
I also discovered that failures in the Observable subscriber would result in test timeouts. That is, the test would fail but it would also timeout because done was never called.
To be resilient in the event of unexpected failure, I think the cat interceptor test should be modified:
```typescript
it('should successfully return', (done) => {
interceptor.intercept({} as any, next).subscribe({
next: (value) => {
try {
expect(value).toEqual({ data: returnCat });
} catch(error) {
fail(error);
}
},
error: (error) => {
fail(error);
},
complete: () => {
done();
},
});
});
```
Contributor guide
Assessment
This issue has not been assessed yet.