添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I trying a lot resolve a problem with Angular 9, Jasmine and RxJS but i don't obten success. My unit test is run by Jasmine but i some lines code don't is executed.

I've been looking for help on several posts, but none of these articles can provide a solution that works for my problem, I'm really frustrated with that.

I need help, please :)

CLASS TEST

describe('AuthRefreshAppInterceptor', () => {
    let accessToken: string;
    let endpoint: string;
    let authAppServiceMock: AuthAppService;
    let baseHTTPService: BaseHTTPService;
    let environmentServiceMock: EnvironmentService;
    let httpTestingController: HttpTestingController;
    let sessionStorageServiceMock: SessionStorageService;
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [
                CriptografiaService,
                BaseHTTPService,
                    provide: AuthAppService,
                    useValue: jasmine.createSpyObj('AuthAppService', ['getNewAuth', 'saveAuth', 'createBodyAuth', 'createBodyAuth'])
                    provide: EnvironmentService,
                    useValue: EnvironmentMock
                    provide: HTTP_INTERCEPTORS,
                    useClass: AutorizacaoErroAppInterceptor,
                    multi: true,
                    provide: SessionStorageService,
                    useValue: jasmine.createSpyObj('SessionStorageService', ['saveItem', 'getItem', 'removeItem'])
        authAppServiceMock = TestBed.inject(AuthAppService);
        baseHTTPService = TestBed.inject(BaseHTTPService);
        environmentServiceMock = TestBed.inject(EnvironmentService);
        httpTestingController = TestBed.inject(HttpTestingController);
        sessionStorageServiceMock = TestBed.inject(SessionStorageService);
        accessToken = faker.finance.bitcoinAddress();
        endpoint = faker.internet.domainName();
        sessionStorageServiceMock.getItem = jasmine.createSpy()
            .and.returnValue({ access_token: accessToken });
    afterEach(() => {
        httpTestingController.verify();
        authAppServiceMock.obterAutorizacaoApp = jasmine.createSpy()
            .and.returnValue(Observable.of({
                access_token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6Ik5oMXY4YlZsODg2M3g3UnhWTlJhamciLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE1OTE3OTU5MjAsImV4cCI6MTU5MTc5OTUyRJhdnjh78sjiHDhdiajsd9sb2NhbGhvc3Q6NTUwMDEiLCJhdWQiOiJJZGVudGl0eVNlcnZlckFwaSIsImNsaWVudF9pZCI6IkFkbWluIiwic2NvcGUiOlsiSWRlbnR86d5F4dasdf.Gvxq02a2HaF4rpeB3KnBxRAHHa6WpU850V5377wpRBAA6rmw6PRzVRMnpd2mtr5CVY72NWCspsdU8a8XhwFTgoCDmjSlXKSZKmUGsEaCbXuzSQg7BwD7A9zul0U0VkbF1KTvLIdnmb1noyeOP04dDH',
                expires_in: 3600,
                token_type: 'Bearer',
                scope: 'IdentityServerApi'
    it('Should executed a request GET and return a HtttpErrorResponse with error 401 Unauthorized', () => {
        spyOn(baseHTTPService, 'httpGet').and.callThrough();
        baseHTTPService.httpGet(endpoint).subscribe({
            error: (httpErrorResponse: HttpErrorResponse) => {
                console.log(httpErrorResponse)
                expect(httpErrorResponse.status).toEqual(401);
                expect(httpErrorResponse.statusText).toEqual('Unauthorized');
                expect(httpErrorResponse.message).toContain('Http failure response for');
        const httpRequest = httpTestingController.expectOne(
            `${environmentServiceMock.apiGatewayURL}/${endpoint}`
        httpRequest.flush(null, { status: 401, statusText: 'Unauthorized' });
        expect(baseHTTPService.httpGet).toHaveBeenCalledTimes(1);
        expect(httpRequest.request.url).toBe(`${environmentServiceMock.apiGatewayURL}/${endpoint}`);
        expect(httpRequest.request.method).toBe('GET');
        expect(httpRequest.request.body).toBeNull();

INTERCEPTOR: TESTED CLASS

export class AuthRefreshAppInterceptor {
    private getNewAuth(request: HttpRequest<any>, next: HttpHandler) {
        return this.authAppService
            .getAuthApp()
            .pipe(
                // THIS BLOCK IS NOT TESTED
                switchMap((auth: AuthAppModel) => {
                    this.authAppService.saveAuth(auth);
                    return next.handle(this.addHeaders(request));
                // THIS BLOCK IS NOT TESTED
                catchError(() => next.handle(request))

SERVICE

export class AuthAppService {
    public salvarAutorizacao(auth: AuthAppModel) {
        this.sessionStorageService.removeItem(this.authKey);
        this.sessionStorageService.saveItem(this.authKey, auth);
    public getAuthApp(): Observable<AuthAppModel> {
        return this.httpClient.post<AuthAppModel>(
            `${this.environmentService.apiGateway}/identity/token`,
            this.createBodyAuth(),
            { headers: this.createHeaders() }

Thank's

provide: AuthAppService, useValue: jasmine.createSpyObj('AuthAppService', ['getAuthApp' 'getNewAuth', 'saveAuth', 'createBodyAuth', 'createBodyAuth']) // add 'getAuthApp' here

For success path (switchMap)

import { of } from 'rxjs';
// at the beginning of you test mock these
authAppServiceMock.getAuthApp.and.returnValue(of({})); // put your mock value here
authAppServiceMock.saveAuth.and.returnValue(of({})); // put your mock value here
... proceed with your test

For fail path (catchError)

import { throwError } from 'rxjs';
// at the beginning of you test mock this
authAppServiceMock.getAuthApp.and.returnValue(throwError({})); // mock your throw error here so it goes into catchError
.... proceed with your test
                Hi @AliF50, thanks for your help o/! Code lines now is coverage but throw error: Expected no open requests, found 1: GET localhost:3777/api/address-endpoint
– Rick
                Nov 16, 2020 at 17:27
                You have a request happening for api/address-endpoint, is that happening on the switchMap? You have to make sure you give a req.flush for that request as well because your httpTestingController.verify(); in the afterEach will fail.
– AliF50
                Nov 16, 2020 at 18:23
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.