A classe ConflictInterceptor()
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, ConflictException } from '@nestjs/common'
import { catchError, Observable } from 'rxjs'
import { ConflictError } from '../types/ConflictError'
@Injectable()
export class ConflictInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
catchError(error => {
if (error instanceof ConflictError) {
throw new ConflictException(error.message)
} else {
throw error
}
}),
)
}
}O teste:
import { ExecutionContext } from '@nestjs/common'
import { CallHandler } from '@nestjs/common/interfaces'
import { lastValueFrom, of } from 'rxjs'
import { ConflictInterceptor } from './conflict.interceptor'
import { createMock } from '@golevelup/ts-jest'
import { ConflictError } from '../types/ConflictError'
describe('ConflictInterceptor', () => {
let interceptor: ConflictInterceptor
beforeEach(() => {
interceptor = new ConflictInterceptor()
})
it('should be defined', () => {
expect(interceptor).toBeDefined()
})
describe('intercept', () => {
it('should return handleConflictErrors', async () => {
const error = new ConflictError()
const context = createMock<ExecutionContext>()
const next = createMock<CallHandler>({
handle: () => of(error),
})
const observable = interceptor.intercept(context, next)
const errorReturned = await lastValueFrom(observable)
//const catchErrorReturned = await lastValueFrom(observable.pipe(catchError(err => of(err))))
expect(error).toEqual(errorReturned)
expect(errorReturned).toBeInstanceOf(ConflictError)
expect(next.handle).toHaveBeenCalledTimes(1)
})
it('should s', async () => {
const context = createMock<ExecutionContext>()
// Arrange
const error = new ConflictError()
// This guarantees our data will be returned to our interceptor
const next = {
handle() {
return of(error)
},
}
interceptor.intercept(context, next).subscribe(data => {
expect(data).toEqual(error)
})
})
})
})Resultado no cpverage
