jeudi 20 septembre 2018

How to make Testing with Angular 6 and Apollo client for GraphQl

I'm trying to make test development with Angular 6 and GraphQl but we really don't know how to do as the best way possible. I have tried to find something on the internet that explains this, but nothing really good has been found.

I'll post my case here looking for someone who could help me to do, or someone who could tell me any tutorial/web to find more and good information.

The problem

I want to test an Auth. I have an auth.service.js and the respective spec.js. You can see it below:

AUTH_SERVICE_TS

import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import * as UserActions from './../../store/user/actions';
import gql from 'graphql-tag';
import { Apollo } from 'apollo-angular';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
    user;

    constructor(private store: Store<any>, private apollo: Apollo, private router: Router) {
        this.store.select('state').subscribe(state => this.user = state);
    }

    /**
     * Function that check the email and password for login
     * @param email
     * @param password
     */
    login(email: string, password: string) {
        this.apollo.mutate({
            mutation: this.loginRequestGql(),
            variables: {
                email: email,
                password: password
            }
        }).subscribe(value => {
            const data = value.data.login;

            this.saveUserData(data);
            this.router.navigate(['/app']);
        });

    }

    /**
     * Function that save user data in the store and in the session storage
     * @param data
     */
    saveUserData(data) {
        this.store.dispatch(new UserActions.Login({token: data.token}));
        this.setSessionStorage(this.user);
    }

    /**
     * Function that remove user info in the store
     */
    logout() {
        this.store.dispatch(new UserActions.Logout());
        this.setSessionStorage(this.user);
    }

    /**
     * Function that create the request with Graphql sintax
     */
    loginRequestGql() {
        return gql`
            mutation Login($email: String!, $password: String!) {
                login(email: $email, password: $password) {
                    token
                }
            }
        `;
    }

    /**
     * Function that save in the session storage the data parameter
     * @param data
     */
    setSessionStorage(data) {
        sessionStorage.setItem('session', JSON.stringify(data));
    }
}

AUTH_SERVICE_SPEC_TS

import { TestBed, inject } from '@angular/core/testing';

import { ApolloTestingController, ApolloTestingModule } from "apollo-angular/testing";
import { RouterTestingModule } from '@angular/router/testing';
import { AuthService } from './auth.service';

import { Store, StoreModule } from '@ngrx/store';
import { reducer } from '../../store/user/reducer';

describe('AuthService', () => {
    let backend: ApolloTestingController;
    let authService: AuthService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [ RouterTestingModule, ApolloTestingModule, StoreModule.forRoot({ state: reducer }) ],
            providers: [ AuthService,
                { provide: ApolloTestingModule, useClass: ApolloTestingModule }
            ]
        });
    });

    beforeEach(() => {
        backend = TestBed.get(ApolloTestingController);
        authService = TestBed.get(AuthService);
    });

    it('should be created', inject([AuthService], (service: AuthService) => {
        expect(service).toBeTruthy();
    }));

    it('should test login', (done) => {
        const email = 'diego@mail.com';
        const password = '123456';

        // const a = authService.login(email, password);
        // expect(a).toBe(TEST_RESPONSE['data'].login.token);
        // authService.login(email, password);
        // backend.expectOne(authService.loginRequestGql).flush(TEST_RESPONSE);
    });
});

const TEST_RESPONSE: Object = {
        "data": {
            "login": {
                "token": "eyJ0eXAiOiJKLCJhbGciOiJSUzI1NiIsImp0aSI6IjZjZDBjMDMXX0.as7-r_nlYfJ2w3CfOqwtLcTlBg5LrwFcm_ZXZ_GzCl5Qq0GS92r5tqGJtFzRfG02PPoLZ8uwsbgLj-5v2pYBXHjBLZvbjnW_zgXRLoDEcrBDpfPAoVH85ca_hb_xVaIgEUGumUPfn2IOx0Ce8fLlqtWGqoWtWzcCE
        }
    };

Thanks in advance to the community!! Hope you can help me!!

PD: If you need more information, just request and i'll give.

Aucun commentaire:

Enregistrer un commentaire