Correct Way To Do Async Calls To Get Test Data From REST End Points Inside Protractor?
We are doing end to end UI testing using Protractor and using Jasmine as BDD framework. We need text of UI to be validated against the data from REST API, for which we are using Axios!! Is this the right approach? Sample code is mentioned below:
import axios from "axios";
describe("Some test for ", () => {
beforeEach(function(done) {
axios
.get(
"******************"
)
.then(response => {
data_file = response.data;
done();
});
});
it("some spec ", done => {
expect($('#someId').getText()).toBe(data_file.someData);
done();
});
});
Can we use Chakram instead of Axios inside Jasmine in Protractor for fetching data?
If the above approaches are wrong, then what is the correct way of testing UI against data from REST end points? (Chai + Mocha + Chakram + Protractor) or anything else?
Answer
It could be. The done()
callback tells Jasmine that you are doing an async task; however, you should be careful to catch the errors.
Adding in done.fail
import axios from "axios";
describe("Some test for ", () => {
beforeEach(function(done) {
axios
.get(
"******************"
)
.then(response => {
data_file = response.data;
done();
})
// if the above fails to .get, then we should catch here and fail with a message
.catch(error => {
done.fail('axios.get failed to execute');
});
});
Better approach. Using async / await
In your Protractor config, you will need to add SELENIUM_PROMISE_MANAGER: false
to enable async / await. This will now require you to await all promises.
import axios from "axios";
describe("Some test for ", () => {
beforeEach(async () => {
try {
const data_file = await axios.get("******************").data;
} catch (e) {
console.error('axios.get failed to execute');
throw e; // throwing errors should fail the spec.
}
});
it("some spec ", async () => {
// .getText returns a Promise<string> so you'll need to await it
// to get the string value.
expect(await $('#someId').getText()).toBe(data_file.someData);
});
});
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM