I'm facing a challenge in Angular 6 e2e tests where I need to execute a POST request to my API within the beforeAll
block. Despite trying various methods, I haven't been successful so far. Below is a description of my situation.
To start, create a new Angular 6 project using the CLI with ng new foobar
and navigate to the project folder. Then, open the app.e2e-spec.ts
file and insert the following code snippet inside the describe
function:
let id: string;
beforeAll((done) => {
fetch('https://example.org/my-api', { method: 'POST' })
.then(r => r.json())
.then(r => {
id = r;
done();
})
.catch(err => done(err));
});
The reason for this action is to add a test subject to the database via the API so that the returned ID can be utilized in subsequent e2e tests.
Unfortunately, an error occurs during execution:
Failed: fetch is not defined
Alternative attempts were made as well. Initially, I tried utilizing native xhr
, but encountered the error:
Failed: XMLHttpRequest is not defined
Next, I experimented with import { http } from 'https';
followed by calling the http.request(...)
function which resulted in failure due to VSCode signaling that
[ts] Module '"https"' has no exported member 'http'.
Lastly, wrapping the fetch
within a browser.executeAsyncScript(...)
call proved ineffective as I couldn't access the result of the POST request outside the browser scope for use in tests.
At this juncture, I am uncertain of the best approach. What would be a recommended method to perform an Ajax POST to the API in the beforeAll
section of an Angular 6 protractor end-to-end test?