【问题标题】:How to make Testing with Angular 6 and Apollo client for GraphQl如何使用 Angular 6 和 Apollo 客户端为 GraphQl 进行测试
【发布时间】:2019-02-24 15:59:48
【问题描述】:

我正在尝试使用 Angular 6 和 GraphQl 进行测试开发,但我们真的不知道如何做到最好。我试图在互联网上找到解释这一点的东西,但没有找到真正好的东西。

我将在此处发布我的案例,寻找可以帮助我的人,或者可以告诉我任何教程/网络以找到更多和好的信息的人。

问题

我想测试一个 Auth。我有一个 auth.service.js 和相应的 spec.js。你可以在下面看到它:

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
        }
    };

提前感谢社区!希望你能帮助我!!

PD:如果您需要更多信息,请提出要求,我会提供。

【问题讨论】:

    标签: testing karma-jasmine angular6 apollo


    【解决方案1】:

    apollo-angular 的最新版本之一中,我们发布了一个测试实用程序。测试技术与在 Angular 中测试 HttpClient 的方式非常相似。

    要了解更多关于如何测试使用 Apollo 的组件和服务,请阅读有关它的官方文档。

    https://www.apollographql.com/docs/angular/guides/testing.html

    【讨论】:

    • 我们找不到关于突变请求的有用测试。也许,我的错误是关于概念的,我不能直接创建突变测试。
    • @DiegoGalocha 没有突变的示例测试,但您可以按操作名称和文档对查询进行完全相同的测试。
    • 这很有帮助!虽然链接已失效,但这里是更新的链接:apollo-angular.com/docs/development-and-testing/testing
    【解决方案2】:

    在进行突变时,我们似乎不能将expectOne 与简单的DocumentNode 参数一起使用。 所以而不是:

    backend.expectOne(authService.loginRequestGql).flush(TEST_RESPONSE);
    

    我们必须将一个函数传递给expectOne,该函数断言操作的查询定义是预期的:

    backend.expectOne((operation) => {
        expect(operation.query.definitions).toEqual(mutation.definitions);
        return true;
    })
    .flush(TEST_RESPONSE);
    

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 2020-08-25
      • 2019-06-10
      • 2019-09-27
      • 2021-05-30
      • 2018-09-15
      • 2019-07-26
      • 2021-10-08
      • 2019-06-22
      相关资源
      最近更新 更多