gpt4 book ai didi

javascript - Angular 2 JWT 单元测试

转载 作者:太空狗 更新时间:2023-10-29 16:53:57 24 4
gpt4 key购买 nike

我的 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

最佳答案

TypeError: null is not an object (evaluating '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']
},

关于javascript - Angular 2 JWT 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42151194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com