Protractor/Jasmine send REST Call when a test failed - rest

I am using Protractor and Jasmine to test my hybrid mobile app, which works fine. I'd like to create an incident on my Team Foundation Server (TFS), when a test fails. Therefore, I have to send an REST-Call to the Api, which also works fine in my Angular App. But it does not work, when I am inside my test environment.
My Code:
var BrowsePage = require('./browse.page');
var tfsIncident = require('./tfsIncident_service');
var request = require('request');
describe('Testing the browse state', function () {
var browsePage = new BrowsePage();
var specsArray = [];
var reporterCurrentSpec = {
specDone: function (result) {
if (result.status === 'failed') {
var mappedResult = tfsIncident.create(result);
console.log(mappedResult); //This works so far, but then it crashes
var options = {
method: 'PATCH', //THis Method requiered the API
url: 'MY_COOL_API_ENDPOINT',
headers: {
'Authorization': 'Basic ' + btoa('USERNAME' + ':' + 'PASSWORD'),
'Content-Type': 'application/json-patch+json'
},
body: mappedResult
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(response);
console.log(info);
}
}
request(options, callback);
}
}
};
jasmine.getEnv().addReporter(reporterCurrentSpec);
//This test passes
it('should be able to take display the heading', function () {
expect(browsePage.headline.isPresent()).toBe(true);
});
// Test is supposed to fail
it('should be able to fail', function () {
expect(browsePage.headline).toBe(1);
});
// Test is supposed to fail as well
it('should be able to fail too', function () {
expect(browsePage.headline).toBe(2);
});
});
So the problem is, that my only console output is (after the console.log(mappedResult)): E/launcher - BUG: launcher exited with 1 tasks remaining
So I have no idea, why this does not work.
Any help appreciated.
Edit
Protractor: 5.0.0
Appium Desktop Client: 1.4.16.1
Chromedriver: 2.27
Windows 10 64 Bit
Jasmine: 2.4.1

I finally got my problem solved. The problem was caused by ignoring the promises by jasmine. I had to add a .controllFlow().wait() to my protractor.promise
The following code works fine:
var BrowsePage = require('./browse.page');
describe('Testing the browse state', function () {
var browsePage = new BrowsePage();
var reporterCurrentSpec = {
specDone: function (result) {
if (result.status === 'failed') {
//Mapping of the result
var incident = [
{
op: 'add',
path: '/fields/System.Title',
value: 'Test: ' + result.fullName + ' failed'
},
{
op: 'add',
path: '/fields/System.Description',
value: result.failedExpectations[0].message
},
{
op: 'add',
path: '/fields/Microsoft.VSTS.Common.Priority',
value: '1'
},
{
op: 'add',
path: '/fields/System.AssignedTo',
value: 'Name Lastname <e#mail.com>'
}
];
protractor.promise.controlFlow().wait(create(incident)).then(function (done) { //The magic happens in this line
console.log("test done from specDone:" + done);
});
}
}
};
jasmine.getEnv().addReporter(reporterCurrentSpec); //Add new Jasmine-Reporter
function create(incident) {
var request = require('request');
var defer = protractor.promise.defer(); //new promise
request({
url: 'https://MY_COOL_ENDPOINT.COM',
method: "PATCH",
json: true, // <--Very important!!!
headers: {
'Authorization': 'Basic ' + new Buffer('USERNAME' + ':' + 'PASSWORD').toString('base64'),
'Content-Type': 'application/json-patch+json'
},
body: incident
}, function (error, response, body) {
console.log(error);
console.log(response.statusCode);
console.log(body.id); //Id of created incident on TFS
defer.fulfill({
statusCode: response.statusCode
}); //resolve the promise
});
return defer.promise; //return promise here
}
it('should be able to display the heading', function () {
expect(browsePage.headline.isPresent()).toBe(true);
});
it('should be able to fail', function () {
expect(browsePage.headline.isPresent()).toBe(false);
});
it('should be able to fail 2', function () {
expect(browsePage.headline.isPresent()).toBe(false);
});
});
Attention
When the test suite is done and the last promise is not resolved at this moment, the last incident is not created. I'll try to work around by adding to the last test a browser.sleep(5000); so that the create(incident) function gets more time to finish.
Thanks to this StackOverflow answer for helping me.

Related

How to call http.post using protractor in typescript

I am trying to do http post in protractor. The status of http.post sits in pending status and doesn't return any response.
I am calling a method in onPrepare function under specDone:
jasmine.getEnv().addReporter({
specDone: function(result) {
if (result.status == "failed") {
browser.getCapabilities().then(function(caps) {
var browserName = caps.get("browserName");
browser.takeScreenshot().then(function(png) {
var stream = fs.createWriteStream(
"./reports/screenshots/" +
browserName +
"-" +
result.fullName +
".png"
);
stream.write(new Buffer(png, "base64"));
stream.end();
});
});
}
new PortalData().PushDataToPortal("");
}
});
Below function in called from onPrepare, the API takes the parameter from body. I am using protractor-http-client package for API calls.
export class PortalData {
public PushDataToPortal(result) {
const http: HttpClient = new HttpClient();
const LogFilePathInSharedLocation =
"\\\\10.101.101.11\\temp\\DocStar\\Automation\\TestLogs\\Logs.txt";
http
.post(
someurl,
LogFilePathInSharedLocation,
{ "Content-Type": "application/x-www-form-urlencoded" }
)
.then((response: ResponsePromise) => {
console.log(response);
});
}
Please advise. Thanks!
I would suggest you use Http call in beforeAll instead of onPrepare.
You can try superagent or supertest npm modules:
Example for superagent
const superagent = require('superagent');
// callback
superagent
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
.set('X-API-Key', 'foobar')
.set('accept', 'json')
.end((err, res) => {
// Calling the end function will send the request
});
// promise with then/catch
superagent.post('/api/pet').then(console.log).catch(console.error);
// promise with async/await
(async () => {
try {
const res = await superagent.post('/api/pet');
console.log(res);
} catch (err) {
console.error(err);
}
})();
Example for supertest
const supertest = require('supertest');
const request = supertest(`${baseURL}`);
request.put('/test/sendlocal')
.send(profileAddressData.createData)
.set('Content-Type', 'application/json')
.set('Accept', '*/*')
.expect(200)
.end((err, res) => {
if (err) {
console.error('Error: ', err);
console.error('Response: ', res);
}
});

Facing issue as 404 while Ajax call in typo3

I am new in typo3 and used the ajaxselectlist extension but while the time usage I am facing 404 not found an error.
Below code is fetch from ajaxselectlist/Resources/Templates/OptionRecord/List.html
<script>
jQuery(document).ready(function ($) {
var form = $('#ajaxselectlist-form');
var selectForm = $('.ajaxFormOption');
var controllerpath = $("#uri_hidden").val();
var resultContainer = $('#ajaxCallResult');
var service = {
ajaxCall: function (data) {
console.log("---->"+data.serialize());
$.ajax({
url: controllerpath,
cache: false,
data: {'uid':'1'},
success: function (result) {
resultContainer.html(result).fadeIn('slow');
},
error: function (jqXHR, textStatus, errorThrow) {
resultContainer.html('Ajax request - ' + textStatus + ': ' + errorThrow).fadeIn('fast');
}
});
}
};
form.submit(function (ev) {
ev.preventDefault();
service.ajaxCall($(this));
});
selectForm.change(function () {
resultContainer.fadeOut('slow');
form.submit();
});
selectForm.trigger('change');
});
</script>

Loopback remoteMethod with onesignal push notification

i still learn, and trying to be learn. im looking for trying hard remote method on loopback 3 for push notification to specific user with onesignal.
any wrong in my code ?
because always :
Error: [ 'All included players are not subscribed' ]
My Case :
im using ionic 3 framework
loopback 3 (or latest)
2 User, (Customer & Seller)
Customer buying product from thread's seller.
If success to order, the seller will receive the notification.
and This is My code :
Ajiorder.observe('after save', function (ctx, next) {
console.log('Order', ctx.instance);
let postingModel = app.models.AjiPosting;
let userAuth = app.models.AjiUserAuth;
postingModel.find({
where:
{ id: ctx.instance.id }
}, function (err, success) {
console.log(success, 'SUKSES');
if (ctx.instance) {
let dataFilter = [];
dataFilter.push({
'field': 'tag',
'key': 'id',
'relation': '=',
'value': success[0].id
});
console.log(success[0].idSeller, 'ID TOT')
console.log(dataFilter, 'dataFilter');
let data = {
idSeller: ctx.instance.idSeller
}
console.log(data, 'Data');
userAuth.find({
where:
{ id: ctx.instance.idCustomer }
}, function (err, result) {
console.log(result, 'Data Personal');
let content = result[0].namaLengkap + ' ' + 'Order your product';
console.log(content, 'Nama Order');
console.log(ctx.instance.idSeller, 'My Dream', success[0].id);
if (ctx.instance.id != success[0].id) {
console.log('Spirit');
sendMessage(dataFilter, content, data);
}
})
}
next();
});
});
var sendMessage = function (device, message, data) {
var restKey = 'XXXXXXXXXXXXXXXXXX';
var appID = 'XXXXXXXXXXXXXXXXX';
request(
{
method: 'POST',
uri: 'https://onesignal.com/api/v1/notifications',
headers: {
'authorization': 'Basic ' + restKey,
'content-type': 'application/json'
},
json: true,
body: {
'app_id': appID,
'filters': device,
'data': data,
'contents': { en: message }
}
},
function (error, response, body) {
try {
if (!body.errors) {
console.log(body);
} else {
console.error('Error:', body.errors);
}
} catch (err) {
console.log(err);
}
}
)
}
};
and i got this error :
Error: [ 'All included players are not subscribed' ]
Picture : Picture of Console Log Here
any one can help me ?
sorry for my english too bad.
Greetings
Solved !
I'm Forget to add some code from onesignal. thanks

Cannot run multiple karma tests using suave server

When I run the below tests individually (by commenting out) then each test passes. However, when I run all tests then I get an XmlHttpRequest uncaught exception. The suave test server receives the requests and the logging shows no errors or problems:
var HOME_URL = "http://localhost:3000/request";
it("should echo the test request with response", function (done) {
var test = { act: 'test1', qry: {} };
var promise = webix.ajax().post(HOME_URL, JSON.stringify(test));
console.log('test1');
promise.then(function (resp) {
expect(resp.json().succ).to.be(true);
done();
}).fail(function (err) {
done();
throw(err);
});
});
it("should echo the test request with response 2", function (done) {
var test = { act: 'test2', qry: {} };
var promise = webix.ajax().post(HOME_URL, JSON.stringify(test));
console.log('test2');
promise.then(function (resp) {
expect(resp.json().succ).to.be(true);
done();
}).fail(function (err) {
console.log('echo test error', app.util.inspect(promise));
done();
throw(err);
});
});
Any ideas what the problem could be or how to debug these tests?
To run the code yourself (git node and npm have to be installed):
git clone http://github.com/halcwb/GenUnitApp.git
cd GenUnitApp
git checkout failingServer
scripts/run.sh
Open second terminal
./build.sh clienttests
For anyone running into this, you can nest the ajax calls in a before function and later on use the promises (webix.ajax returns a promise) in your tests like:
var HOME_URL = "http://localhost:3000/request";
var test1, test2;
before(function () {
var req = { act: 'test1', qry: {}};
test1 = webix.ajax().post(HOME_URL, JSON.stringify(req));
req.act = "test2";
test2 = webix.ajax().post(HOME_URL, JSON.stringify(req));
});
it("should echo the test request with response", function (done) {
var promise = test1;
promise.then(function (resp) {
expect(resp.json().succ).to.be(true);
done();
}).fail(function (err) {
done();
throw(err);
});
});
it("should echo the test request with response 2", function (done) {
var promise = test2;
promise.then(function (resp) {
expect(resp.json().succ).to.be(true);
done();
}).fail(function (err) {
done();
throw(err);
});
});

Using QUnit and sinon.spy, how can I access my spy within an async callback?

I am new to QUnit and sinon.js and working to build tests for an ember-cli package. I am having problems getting sinon.spy(Ember.run, 'later') to work with the code below. inside the callback Ember.run.later is not being spied / has no .getCalls() etc...
How can I handle this type of test?
test('#authenticate rejects with invalid credentials', function() {
sinon.spy(Ember.run, 'later');
var jwt = JWT.create(),
expiresAt = (new Date()).getTime() + 60000;
var token = {};
token[jwt.identificationField] = 'test#test.com';
token[jwt.tokenExpireName] = expiresAt;
token = window.btoa(JSON.stringify(token));
var credentials = {
identification: 'username',
password: 'password'
};
App.server.respondWith('POST', jwt.serverTokenEndpoint, [
400,
{
'Content-Type': 'application/json'
},
'{"message":["Unable to login with provided credentials."]}'
]);
Ember.run(function(){
App.authenticator.authenticate(credentials).then(null, function(){
// Check that Ember.run.later was not called.
equal(Ember.run.later.getCall(0), null);
});
});
Ember.run.later.restore();
});
PS I currently am able to get this working by moving the sinon.spy and corresponding Ember.run.later.restore() to the module.setup() and module.teardown() methods respectively. Is there anything wrong with that that strategy other than it means they are spied for every test in my suite?
Thanks!
EDIT: Here is my authenticate method:
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var data = _this.getAuthenticateData(credentials);
_this.makeRequest(_this.serverTokenEndpoint, data).then(function(response) {
Ember.run(function() {
var tokenData = _this.getTokenData(response),
expiresAt = tokenData[_this.tokenExpireName];
_this.scheduleAccessTokenRefresh(expiresAt, response.token);
response = Ember.merge(response, { expiresAt: expiresAt });
resolve(_this.getResponseData(response));
});
}, function(xhr) {
Ember.run(function() {
reject(xhr.responseJSON || xhr.responseText);
});
});
});
},