Как я могу использовать Angular HttpClient для написания тестов e2e для моего API бэкэнда?
Я хочу написать несколько тестов для моего серверного API. Поскольку мой внешний интерфейс - Angular, у меня уже есть полная среда тестирования в моей среде, и я подумал, что было бы лучше использовать это, а не импортировать и изучать что-то новое (если бы я выполнял модульные тесты, мне понадобился бы собственный механизм тестирования)., но я просто хочу проверить http интерфейс здесь).
Чтобы не усложнять мой вопрос, давайте забудем о моем бэк-энде и просто воспользуемся здесь публичным API ( People-In-Space).
С Angular CLI легко создать новое приложение, добавить суперагент и написать тест:
api.e2e-spec.ts
import * as superagent from 'superagent';
describe('people-in-space API', () => {
it('should report success getting a list of people in space', (done) => {
superagent.get('http://api.open-notify.org/astros.json').then((response: superagent.Response) => {
expect(response.body.message).toEqual('success');
done();
}).catch(done.fail);
});
});
Это работает нормально, и вы можете найти его в этом хранилище.
Теперь я рад, что обо всем этом поговорим, но в идеале я не думаю, что мне следует использовать суперагент в качестве http-клиента, потому что весь остальной код будет использовать HttpClient от Angular.
Что именно мне нужно настроить, прежде чем я смогу переписать вышеуказанный тест с помощью HttpClient, пожалуйста?
Что я пробовал до сих пор
Вы можете найти мою попытку решить проблему здесь. Я:
- Написан тест
- Добавлен zone.js в мой файл protractor.conf.js
- Попытка импортировать модуль HttpClient (и при этом похоже, что я сломал некоторую другую зависимость)
Я получаю ошибку:
> people-in-space@0.0.0 e2e C:\git\people-in-space
> ng e2e
** NG Live Development Server is listening on localhost:49152, open your browser on http://localhost:49152/ **
[0mDate: [1m[37m2018-01-04T21:43:44.807Z[39m[22m[0m
[0mHash: [1m[37m6929b70a097b5cdc054b[39m[22m[0m
[0mTime: [1m[37m7234[39m[22mms[0m
[0mchunk {[1m[33minline[39m[22m} [1m[32minline.bundle.js, inline.bundle.js.map[39m[22m (inline) 5.83 kB [1m[33m[entry][39m[22m[1m[32m [rendered][39m[22m[0m
[0mchunk {[1m[33mmain[39m[22m} [1m[32mmain.bundle.js, main.bundle.js.map[39m[22m (main) 8.54 kB [1m[33m[initial][39m[22m[1m[32m [rendered][39m[22m[0m
[0mchunk {[1m[33mpolyfills[39m[22m} [1m[32mpolyfills.bundle.js, polyfills.bundle.js.map[39m[22m (polyfills) 202 kB [1m[33m[initial][39m[22m[1m[32m [rendered][39m[22m[0m
[0mchunk {[1m[33mstyles[39m[22m} [1m[32mstyles.bundle.js, styles.bundle.js.map[39m[22m (styles) 11.4 kB [1m[33m[initial][39m[22m[1m[32m [rendered][39m[22m[0m
[0mchunk {[1m[33mvendor[39m[22m} [1m[32mvendor.bundle.js, vendor.bundle.js.map[39m[22m (vendor) 2.66 MB [1m[33m[initial][39m[22m[1m[32m [rendered][39m[22m[0m
(node:18016) [DEP0022] DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
webpack: Compiled successfully.
[21:43:45] I/update - chromedriver: file exists C:\git\people-in-space\node_modules\protractor\node_modules\webdriver-manager\selenium\chromedriver_2.34.zip
[21:43:45] I/update - chromedriver: unzipping chromedriver_2.34.zip
[21:43:45] I/update - chromedriver: chromedriver_2.34.exe up to date
[21:43:45] I/launcher - Running 1 instances of WebDriver
[21:43:45] I/direct - Using ChromeDriver directly...
Jasmine started
people-in-space API
[31m× should report success getting a list of people in space[39m
[31m- [39m[31mFailed: Cannot read property 'getComponentFromError' of null[39m
at TestBed._initIfNeeded (C:\git\people-in-space\node_modules\packages\core\esm5\testing\src\test_bed.js:400:22)
at TestBed.get (C:\git\people-in-space\node_modules\@angular\core\bundles\core-testing.umd.js:1071:14)
at Function.TestBed.get (C:\git\people-in-space\node_modules\@angular\core\bundles\core-testing.umd.js:863:29)
at UserContext.<anonymous> (C:\git\people-in-space\e2e\api.e2e-spec.ts:11:24)
at new ManagedPromise (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:1067:7)
at ControlFlow.promise (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2396:12)
at TaskQueue.execute_ (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2970:14)
at TaskQueue.executeNext_ (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2953:27)
at asyncRun (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2860:25)
at C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:676:7
at ZoneDelegate.invoke (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:388:26)
at Zone.run (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:138:43)
at C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:870:57
at ZoneDelegate.invokeTask (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:421:31)
From: Task: Run beforeAll in control flow
at Function.promise (C:\git\people-in-space\node_modules\protractor\node_modules\q\q.js:682:9)
From asynchronous test:
Error
at Suite.<anonymous> (C:\git\people-in-space\e2e\api.e2e-spec.ts:9:5)
at Object.<anonymous> (C:\git\people-in-space\e2e\api.e2e-spec.ts:5:1)
at Module._compile (module.js:635:30)
at Module.m._compile (C:\git\people-in-space\node_modules\ts-node\src\index.ts:392:23)
at Module._extensions..js (module.js:646:10)
at Object.require.extensions.(anonymous function) [as .ts] (C:\git\people-in-space\node_modules\ts-node\src\index.ts:395:12)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
[31m- [39m[31mFailed: Cannot read property 'assertPresent' of undefined[39m
at resetFakeAsyncZone (C:\git\people-in-space\node_modules\@angular\core\bundles\core-testing.umd.js:401:19)
at UserContext.<anonymous> (C:\git\people-in-space\node_modules\packages\core\esm5\testing\src\before_each.js:25:12)
at new ManagedPromise (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:1067:7)
at ControlFlow.promise (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2396:12)
at TaskQueue.execute_ (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2970:14)
at TaskQueue.executeNext_ (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2953:27)
at asyncRun (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2860:25)
at C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:676:7
at ZoneDelegate.invoke (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:388:26)
at Zone.run (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:138:43)
at C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:870:57
at ZoneDelegate.invokeTask (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:421:31)
at Zone.runTask (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:188:47)
at drainMicroTaskQueue (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:594:35)
From: Task: Run beforeEach in control flow
at ControlFlow.emit (C:\git\people-in-space\node_modules\selenium-webdriver\lib\events.js:62:21)
at ControlFlow.shutdown_ (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2565:10)
From asynchronous test:
Error
at C:\git\people-in-space\node_modules\@angular\core\bundles\core-testing.umd.js:1283:15
at Object.setPrototypeOf.__proto__ (C:\git\people-in-space\node_modules\tslib\tslib.es6.js:1:1)
at Object.<anonymous> (C:\git\people-in-space\node_modules\@angular\core\bundles\core-testing.umd.js:10:2)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (C:\git\people-in-space\e2e\api.e2e-spec.ts:1:1)
at Module._compile (module.js:635:30)
at Module.m._compile (C:\git\people-in-space\node_modules\ts-node\src\index.ts:392:23)
at Module._extensions..js (module.js:646:10)
at Object.require.extensions.(anonymous function) [as .ts] (C:\git\people-in-space\node_modules\ts-node\src\index.ts:395:12)
[31m- [39m[31mFailed: Cannot read property 'get' of null[39m
at UserContext.<anonymous> (C:\git\people-in-space\e2e\api.e2e-spec.ts:26:14)
at new ManagedPromise (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:1067:7)
at ControlFlow.promise (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2396:12)
at TaskQueue.execute_ (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2970:14)
at TaskQueue.executeNext_ (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2953:27)
at asyncRun (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2860:25)
at C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:676:7
at ZoneDelegate.invoke (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:388:26)
at Zone.run (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:138:43)
at C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:870:57
at ZoneDelegate.invokeTask (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:421:31)
at Zone.runTask (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:188:47)
at drainMicroTaskQueue (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:594:35)
at <anonymous>
From: Task: Run it("should report success getting a list of people in space") in control flow
at ControlFlow.emit (C:\git\people-in-space\node_modules\selenium-webdriver\lib\events.js:62:21)
at ControlFlow.shutdown_ (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2565:10)
at shutdownTask_.MicroTask (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2490:53)
at MicroTask.asyncRun (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2619:9)
at C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:676:7
at ZoneDelegate.invoke (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:388:26)
at Zone.run (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:138:43)
at C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:870:57
From asynchronous test:
Error
at Suite.<anonymous> (C:\git\people-in-space\e2e\api.e2e-spec.ts:25:5)
at Object.<anonymous> (C:\git\people-in-space\e2e\api.e2e-spec.ts:5:1)
at Module._compile (module.js:635:30)
at Module.m._compile (C:\git\people-in-space\node_modules\ts-node\src\index.ts:392:23)
at Module._extensions..js (module.js:646:10)
at Object.require.extensions.(anonymous function) [as .ts] (C:\git\people-in-space\node_modules\ts-node\src\index.ts:395:12)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
people-in-space App
[31m× should display welcome message[39m
[31m- [39m[31mFailed: Cannot read property 'assertPresent' of undefined[39m
at resetFakeAsyncZone (C:\git\people-in-space\node_modules\@angular\core\bundles\core-testing.umd.js:401:19)
at UserContext.<anonymous> (C:\git\people-in-space\node_modules\packages\core\esm5\testing\src\before_each.js:25:12)
at new ManagedPromise (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:1067:7)
at ControlFlow.promise (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2396:12)
at TaskQueue.execute_ (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2970:14)
at TaskQueue.executeNext_ (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2953:27)
at asyncRun (C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:2860:25)
at C:\git\people-in-space\node_modules\selenium-webdriver\lib\promise.js:676:7
at ZoneDelegate.invoke (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:388:26)
at Zone.run (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:138:43)
at C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:870:57
at ZoneDelegate.invokeTask (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:421:31)
at Zone.runTask (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:188:47)
at drainMicroTaskQueue (C:\git\people-in-space\node_modules\zone.js\dist\zone-node.js:594:35)
From: Task: Run beforeEach in control flow
From asynchronous test:
Error
at C:\git\people-in-space\node_modules\@angular\core\bundles\core-testing.umd.js:1283:15
at Object.setPrototypeOf.__proto__ (C:\git\people-in-space\node_modules\tslib\tslib.es6.js:1:1)
at Object.<anonymous> (C:\git\people-in-space\node_modules\@angular\core\bundles\core-testing.umd.js:10:2)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (C:\git\people-in-space\e2e\api.e2e-spec.ts:1:1)
at Module._compile (module.js:635:30)
at Module.m._compile (C:\git\people-in-space\node_modules\ts-node\src\index.ts:392:23)
at Module._extensions..js (module.js:646:10)
at Object.require.extensions.(anonymous function) [as .ts] (C:\git\people-in-space\node_modules\ts-node\src\index.ts:395:12)
**************************************************
* Failures *
**************************************************
1) people-in-space API should report success getting a list of people in space
[31m- [39m[31mFailed: Cannot read property 'getComponentFromError' of null[39m
[31m- [39m[31mFailed: Cannot read property 'assertPresent' of undefined[39m
[31m- [39m[31mFailed: Cannot read property 'get' of null[39m
2) people-in-space App should display welcome message
[31m- [39m[31mFailed: Cannot read property 'assertPresent' of undefined[39m
Executed 2 of 2 specs[31m (2 FAILED)[39m in 1 sec.
[21:43:49] I/launcher - 0 instance(s) of WebDriver still running
[21:43:49] I/launcher - chrome #01 failed 2 test(s)
[21:43:49] I/launcher - overall: 2 failed spec(s)
[21:43:49] E/launcher - Process exited with error code 1
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! people-in-space@0.0.0 e2e: `ng e2e`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the people-in-space@0.0.0 e2e script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\akb\AppData\Roaming\npm-cache\_logs\2018-01-04T21_43_49_504Z-debug.log
1 ответ
Я обнаружил, что могу использовать HttpClient в тесте e2e, если обойду инъекцию зависимостей Angular.
npm install xmlhttprequest
api.e2e-spec.ts
import { HttpClient, HttpXhrBackend, XhrFactory, HttpErrorResponse} from '@angular/common/http';
import { XMLHttpRequest} from 'xmlhttprequest';
export class BrowserXhr implements XhrFactory {
constructor() {}
build(): any { return <any>(new XMLHttpRequest()); }
}
describe('people-in-space API', () => {
const http: HttpClient = new HttpClient(new HttpXhrBackend(new BrowserXhr()));
it('should report success getting a list of people in space', (done) => {
http.get('http://api.open-notify.org/astros.json').subscribe((response: any) => {
expect(response.message).toEqual('success');
done();
}, (error: HttpErrorResponse) => {
done.fail(error.message);
});
});
});