Sinon js call for PUT or POST methods - javascript

I am using sinon js in my project for fake server call. Its working fine for GET calls but I have a scenario in which I want to mock a server with PUT or POST call.
I am doing it in this way:
server = sinon.fakeServer.create();
server.respondWith('PUT', /\/administration\/email/,
[204, { "Content-Type": "application/json" }, JSON.stringify(EmailModelFixture)]);
emailView.save("abc#gmail.com");
server.respond();// Responding that save call.
But this is not working. Any one know how to fix it?

I've checked this scenario and it looks ok to me, so it works well.
Here is an example for Backbone
test("should submit PUT request", function() {
var server = sinon.fakeServer.create();
server.respondWith('PUT', /\/administration\/email/,
[204, { "Content-Type": "application/json" }, JSON.stringify({a:"1"})]);
var spy_done = sinon.spy();
var spy_fail = sinon.spy();
var model = new (Backbone.Model.extend({
url: "/administration/email/"
}));
// Save new model to generate PUT request
model.save({ id: "test" }, {
success: spy_done,
error: spy_fail
});
server.respond();
expect(spy_done.called).to.be.true;
expect(spy_fail.called).to.be.false;
});
I'd recommend you to debug your ajax requests by dumping server.requests and check for url and method there to understand what's wrong.

Related

K6 Use POST to login in

Ive been working with K6 recently and need to test my API, the login function needs a json in order to get the data but it does not get called on the run, heres my code for the script
import http from 'k6/http';
import { sleep } from 'k6';
export default function () {
let strGlobalUrl = '192.168.0.1';
let url = 'http://'+strGlobalUrl+'/api/CompanyLogin';
let data = JSON.stringify({
strEmail : 'email',
strPassword : 'password',
boolLoginPage : true
});
let params = {
headers: {
'Content-Type': 'application/json',
'dataType': 'json'
}
};
let res = http.post(url, data, params);
console.log(res.intResponse);
}
It should call the function and get print 200 on the console log, theres something I do wrong or is missing?
I got the answer from my boss, I forgot to include ':5050' in the value of strGlobalUrl due Im testing in my local copy of the server
I hope this would help someone else

Why is node.js not generating an email with guerrillamail?

I am writing code that creates an email address with guerrillamail.
But, the code I created below:
var request = require('request');
var jar = request.jar();
request({
uri: 'http://api.guerrillamail.com/ajax.php',
method: 'GET',
proxy: proxy,
jar: jar,
form: {
"f": "get_email_address"
}
}, function(e, response, b) {
console.log(b);
});
Only logs :
ERR_INVALID_REQ
In body when I log it. How can I get this to work?
probably need a POST request not GET try changing the method

Sharepoint REST api returns Bad Request (400)

I am trying to create a ListItem using the Sharepoint REST Api (we just started with the Sharepoint Api so definitly no expert).
According to the Microsoft tutorial the post should look like this:
I implemented the following code
public addItemToList_Test(): void {
var listTitle: string = "DemoHomeWork";
var listItemType: string = "SP.Data." + listTitle + "ListItem";
var listItemTitle: string = "TestItem";
var postBody = { '__metadata': { 'type': listItemType }, 'Title': 'TestItem' };
var $: jQuery = require("jquery");
var call = $.ajax({
url: listsUrl + "/GetByTitle('" + listTitle + "')/items",
method: "POST",
body: postBody,
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
length: JSON.stringify(postBody).length
}
});
return call;
}
However, this keeps returning me Bad Request (400) and figuring out why this happens is tricky to find out. Is there anyone who can tell me what is wrong with the request?
How are you authenticating your request?
As given in documentation you need to pass access_token with your request to make API work. As in you headers, i am not seeing access_token being passed.
You need to first get access_token and then pass it with the request to make API work.
Also in
"'__metadata': { 'type': listItemType }" **listItemType** you are creating it manually but it can be different. Can you check getting it manually (`https://site_url/_api/web/lists/getbytitle(listtitle)`)
and check if ListItemEntityTypeFullName for this list is same as you have created listItemType.

Express.js http call inside route doesn't update variable

I'm building a REST api on top of express.js. I am having trouble updating variables inside my routes.
Example:
I'm calling app.get("/wp/page/create/:id", function(req, res)
Inside this route I start by calling a http request using request-promise library. The response of this call I use in a nested http call.
I use a global variable for the headers for the nested call, and it's to the header a i need to make changes by using the etag variable.
Code:
global.postHeaders = headers;
postHeaders['X-HTTP-Method'] = "MERGE";
postHeaders['Content-Type'] = 'application/json;odata=verbose';
postHeaders['X-RequestDigest'] = spContext;
request.get({
url: "xxx",
headers: headers,
json: true
}).then(function(response) {
var etag = response.d.__metadata.etag
postHeaders['If-Match'] = etag;
request.post({
url: "xxx",
type: "POST",
body: data,
headers: postHeaders,
json: true
}).then(function(data) {
res.send(data).end()
console.log("All done!");
})
})
When i start the server up and enter the route everything works fine. When i when try to hit it again the etag variables is still the same, even though it should be updated.
If I restart the server it works the again on the first attempt but fails on the second/third.
Any idea what I am doing wrong?
I have resolved the issues. The simple solution was to clear the headers containing the variable.
global.postHeaders = headers;
postHeaders['X-HTTP-Method'] = "MERGE";
postHeaders['Content-Type'] = 'application/json;odata=verbose';
postHeaders['X-RequestDigest'] = spContext;
request.get({
url: "xxx",
headers: headers,
json: true
}).then(function(response) {
var etag = response.d.__metadata.etag
postHeaders['If-Match'] = etag;
request.post({
url: "xxx",
type: "POST",
body: data,
headers: postHeaders,
json: true
}).then(function(data) {
postHeaders['If-Match'] = "";
res.send(data).end()
console.log("All done!");
})
})
postHeaders is a global variable. is headers in global.postHeaders = headers; also a global varaible ? Whatever you are trying to do here is grossly wrong. postHeaders variable will be shared across multiple request. so you will hit a scenario where postHeaders['If-Match'] value might be empty string or the etag .
Try this instead of the first line
var postHeaders = Object.assign({}, headers);
Not sure what you are trying, but at-least this statement will subside the huge error in the code. This will create a new header object for each request.

Migrating from http to ngResource Angular

It's been 3months since I've used angular and I'm loving it. Finished an app using it and now I'm on a code refactoring or improving my code for better practice. I have an Api service.js that used $http and I want to migrate it to using $resource :)
I have here a sample of my api code using $http:
Service.js
authenticatePlayer: function(postData) {
return $http({
method : 'POST',
url : api + 'auth/player',
data : postData,
headers : {'Content-Type' : 'application/json'}
});
},
#Controller.js
Api.authenticatePlayer(postData).then(function (result){
//success
}, function(result) {
//error also this will catch error 400, 401, and 500
});
The above code are working and now here is my first attempt on using $resource:
authenticate: function() {
return $resource(api + "auth/:usertype",
{
typeOfUser : "#usertype" //types can be player, anonymous, admin
},
{
post : { method : "POST" }
}
);
}
#Controller
var postData = {
email : scope.main.email,
password : scope.main.password
};
var loginUser = new Api(postData);
loginUser.$post(); //error T__T
That just how far I get, don't know how to pass a data to my api using $resource from my controller. That just one part of my api call, there's still a bunch of it but for now this will do. :D.
Any help is greatly appreciated.
Thanks
You could try this:
API
authenticate: function(){
return $resource(api+"auth/:usertype",{},post:{method:"POST"});
}
Note: :usertype in URL means that the value of usertype property which you passed into postData will replace the part of URL
Controller
var postData = {email:scope.main.email,password:scope.main.password};
API.authenticate().post({usertype:'player'},postData,function(response){
console.log(response);
});
Or you could fetch response like this:
var response = API.authenticate().post({usertype:'player'},postData);
Hope this is helpful.

Categories