Angular 2 JWT 单元测试

Posted

技术标签:

【中文标题】Angular 2 JWT 单元测试【英文标题】:Angular 2 JWT Unit Testing 【发布时间】:2017-06-28 07:38:17 【问题描述】:

我的 API 调用已通过 JWT 进行身份验证。我正在尝试为服务方法编写代码。所有请求都有这个拦截器:

public interceptBefore(request: InterceptedRequest): InterceptedRequest 
        // Do whatever with request: get info or edit it
        this.slimLoadingBarService.start();
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (currentUser && currentUser.data.token) 
            request.options.headers.append('Authorization', 'Bearer ' + currentUser.data.token);
        
        return request;
    

我要测试的服务方法:

getAll(page: number, pageSize: number, company: string): Observable<any> 
        return this.http.get(`$this.conf.apiUrl/jobs`)
            .map((response: Response) => response.json());
    

为它启动了代码:

import  MockBackend, MockConnection  from '@angular/http/testing';
import  Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod  from '@angular/http';
import  JobListService  from './job-list.service';
import  inject, TestBed  from '@angular/core/testing/test_bed';
import  JOBLISTMOCK  from '../mocks/job-list.mock';

fdescribe('Service: JobListService', () => 
    beforeEach(() => 
        TestBed.configureTestingModule(
            providers: [
                JobListService,
                MockBackend,
                BaseRequestOptions,
                
                    provide: Http,
                    useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => 
                        return new Http(backend, defaultOptions);
                    ,
                    deps: [MockBackend, BaseRequestOptions]
                ,
            ]
        );
    );

    it('should create a service', inject([JobListService], (service: JobListService) => 
        expect(service).toBeTruthy();
    ));

    describe('getAll', () => 
        it('should return jobs', inject([JobListService, MockBackend], (service: JobListService, backend: MockBackend) => 
            let response = new ResponseOptions(
                body: JSON.stringify(JOBLISTMOCK)
            );

            const baseResponse = new Response(response);

            backend.connections.subscribe(
                (c: MockConnection) => c.mockRespond(baseResponse)
            );

            return service.getAll(1, 10, '18').subscribe(data => 
                expect(data).toEqual(JOBLISTMOCK);
            );
        ));
    );
);

不知道如何针对拦截器进行测试。

PS:由于现在的测试,得到一个错误:

1) should create a service
     JobListService
     TypeError: null is not an object (evaluating 'this.platform.injector') in src/test.ts (line 83858)
_createCompilerAndModule@webpack:///~/@angular/core/testing/test_bed.js:254:0 <- src/test.ts:83858:44

2) should return jobs
     JobListService getAll
     TypeError: null is not an object (evaluating 'this.platform.injector') in src/test.ts (line 83858)
_createCompilerAndModule@webpack:///~/@angular/core/testing/test_bed.js:254:0 <- src/test.ts:83858:44

【问题讨论】:

【参考方案1】:

TypeError: null 不是对象(评估 'this.platform.injector')

如果您没有正确初始化测试环境,通常会出现此错误。您可以通过执行以下操作来解决此问题

import 
  BrowserDynamicTestingModule, platformBrowserDynamicTesting
 from '@angular/platform-browser-dynamic/testing';
...
beforeAll(() => 
  TestBed.initTestEnvironment(
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting()
  );
);

不过,关于这个的事情是,它应该只在整个测试套件执行中被调用一次。所以如果你在每个测试文件中都有它,那么你需要先在每个文件中重置它

beforeAll(() => 
  TestBed.resetTestEnvironment();
  TestBed.initTestEnvironment(
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting()
  );
);

不过,比这更好的是不要在每个测试文件中添加它。如果您查看用于 Webpack 集成的 Angular 文档,在 testing section 中,您将看到一个文件 karma-test-shim.js。在这个文件中是初始化测试环境的推荐方式

Error.stackTraceLimit = Infinity;

require('core-js/es6');
require('core-js/es7/reflect');

require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy');
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');

var appContext = require.context('../src', true, /\.spec\.ts/);

appContext.keys().forEach(appContext);

var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');

testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule,
    browser.platformBrowserDynamicTesting());

您可以在底部看到我们进行与上述相同的初始化调用。您应该将此文件添加到配置中files 数组中的karma.conf.js 文件中。这是来自上面的链接文档

files: [
  pattern: './config/karma-test-shim.js', watched: false
],

preprocessors: 
  './config/karma-test-shim.js': ['webpack', 'sourcemap']
,

【讨论】:

以上是关于Angular 2 JWT 单元测试的主要内容,如果未能解决你的问题,请参考以下文章

使用 Web API 对 JWT 令牌进行单元测试

Angular 2 单元测试组件,模拟 ContentChildren

使用 Angular 2 添加 Firebase 的单元测试

Angular 2 单元测试:找不到名称“描述”

在 Angular 2 中编写最基本的单元测试?

在 Angular 2 中对 observable 进行单元测试