How to mock $.ajax call in JEST - reactjs

I am new to React & JEST framework, I tried doing ajax call in react as below, if i receives a success data it will redirect to home page else an error message is displayed.
let params ={
userName : this.state.userName,
password : this.state.passWord
};
$.ajax({
url: '/reactApp/login',
dataType: 'json',
contentType: 'application/json;',
type: 'POST',
data: JSON.stringify(params),
success: function (successData) {
if (typeof(Storage) !== "undefined") {
localStorage.setItem('userProfile', JSON.stringify(successData));
browserHistory.push('/reactApp/Home');
} else {
alert("The browser version is not supported.Please use Internet explorer 11, Chrome or firefox.")
}
}.bind(this),
error: function(errorData){
this.setState({
errorMessage: errorData.message,
errorDisplay: true,
});
}.bind(this);
The react code is working, i tried to write an unit test in JEST for the above code for ajax call as below,
jest.unmock('jquery');
jest.unmock('./AjaxLogin');
var $ = require('jquery');
const Login = TestUtils.renderIntoDocument(<AjaxLogin />);
expect(Login).toBeDefined();
var handleClick = jest.genMockFunction();
var button = TestUtils.findRenderedDOMComponentWithTag(Login, 'button');
TestUtils.Simulate.click(button);
Login.handleClick();
expect($.ajax).toBeCalledWith({
url: '/reactApp/login',
dataType: 'json',
contentType: 'application/json;',
type: 'POST',
data: JSON.stringify({userName : 'testing', password : 'password'}),
success: jasmine.any(Function),
error: jasmine.any(Function)
});
When i run this test case, i received an below error message, i don't know what is wrong in the above code.
Expected Function to be called with Object
can anyone please help me to identify the issue in unit test script.

unmock method removes mock so you need to use Jest mock method instead.
Jest repo has several examples describing the basic usage including how to mock jquery as well as how to use with react so it is worth looking at.

Related

How to send a POST request with variables in React?

I am learning how to send a POST request to an API with React.
What I'm trying to achieve right now is sending a POST request to an API.
The API will insert the event with something like this (what is this method called?):
https://api.com/WebService.asmx/insertEvent?event_id=5&desc=<p>HelloWorld</p>&name=testing
The method that I'm currently using as POST is shown at POST method and it returns me with the error unexpected token '<' in json at position 0 and the result that I get when I console.log(JSON.stringify(event)) is something like this:
{"event_id":"5","desc":"<p>HelloWorld</p>","name":"testing"}```
POST method
const response = await fetch('https://api.com/WebService.asmx/insertEvent',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(event)
})
Edit: I've fixed the above error by encoding the HTML that I need to send. This is now my latest POST method, but I'm still facing error 500 for some reason even though it works when I copy and pasted the URL+params from the console.log that has the error shown:
const addBulletin = async (event) => {
console.log(event, '--event')
const url = 'https://api.com/WebService.asmx/insertEvent';
axios.post(url, null, { params: {
title: event.title,
desc: event.desc,
image: event.image,
employee: event.employee,
entity: event.entity,
startDate: event.startDate,
endDate: event.endDate,
createdBy: event.createdBy
}})
.then(response => console.log(response.status))
.catch(err => console.warn(err));
};
Edit: I've tested the API on a vanilla JS project using .ajax with POST, and it works, so I think the API shouldn't be a problem.
var json = $('.insert-form').serialize();
$.ajax({
type: "POST",
url: "https://api.com/WebService.asmx/insertEvent",
data: json,
async: true,
success: function (response) {
alert("Event has been successfully created!");
},
error: function (response) {
console.log(response);
}
});
The API you are sending the request to expects a query parameter (data in the URL).
https://api.com/WebService.asmx/insertEvent?event_id=5&desc=<p>HelloWorld</p>&name=testing
In this request, we are sending 3 query params: event_id, desc, and name.
To send this kind of request from React, you should not use request body. Instead. I advise you to use axios to make it easier. It's a very powerful library, better than using fetch. It should be done this way:
axios.post(`https://api.com/WebService.asmx/insertEvent`, null, { params: {
event_id: eventId,
desc
}})
.then(response => response.status)
.catch(err => console.warn(err));
This may help: How to post query parameters with Axios?

jQuery steps submit form -> step turns red

After submitting my form, jQuery steps seems to consider the submit as failed. The last step turns red.
I did not find any documentation on this topic.
Is the plugin expecting a particular response (type) from the server?
onFinishing: function() {
debugger;
var formData = $("#wizardSumbit").serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Wizard_Submit", "Wizard")', //serverside
data: formData,
beforeSend: function () {
//show loading image
},
success: function (result) {
console.log(result); //use this to see the response from serverside
},
error: function (e) {
console.log(e); //use this to see an error in ajax request
}
});
}
I am a little bit confused here.
jQuery steps is considering the submit as failed because of the missing return=true statement in the event.

Using "$http.get" in ionic App, Response not get proper format

I am using "$http.get" for send request. My API response in browser, it returns what i want. But in Ionic App, it return HTML body tag text.
My Code is:
var params = {
email: 'test#gmail.com',
password: '123'
}
$http.get("https://www.nepalivivah.com/API/index.php/accessapi/loginapi", { params: params }).then(function (data) {
alert(JSON.stringify(data));
}).error(function (data) {
alert(JSON.stringify(data));
});
This is my AngularCode. When i run it in postman, it return valid response. But in Ionic App not Working.
If you want the $http.get, this should work.
var params = {
email: 'test#gmail.com',
password: '123'
}
$http.get("https://www.nepalivivah.com/API/index.php/accessapi/loginapi").then(function (data) {
alert(JSON.stringify(data));
}).error(function (err) {
alert(JSON.stringify(err));
});
However, in this case, what you are trying to do is to login into something. A get request will not work with this. You need to use $http.post at least in this case.

how to get results of my webservice with jsonp?

I want to call one of my webservices via jsonp with angularjs.
When i call http://example.com/files?callback=JSON_CALLBACK directly in my browser, i got :
["folder1", "folder2"]
When i call from angularjs with :
$http.jsonp('http://example.com/files?callback=JSON_CALLBACK')
.success(function(data){
console.log(data);
$scope.folders = data;
});
console.log does not appear....
What am i doing wrong ?
Must my webservice return
JSON_CALLBACK(["folder1", "folder2"])
? Should i do it manually in my api ? browser don't do that automatically ?
What you are currently returning (["folder1", "folder2"]) is not valid JSONP. The JSON result must be wrapped by a javascript function call in order to be valid JSONP.
For example, when you use the URL like this:
http://example.com/files?callback=JSON_CALLBACK
Angular will replace the JSON_CALLBACK parameter with an angular function name (created internally), like:
http://example.com/files?callback=angular.callbacks._0
Your server would then need to be able to read that callback parameter and return the result like this:
angular.callbacks._0(["folder1", "folder2"]);
This is not an automatic mechanism, you need to implement that logic on your web server.
Try Using Following code snippet.
(function($) {
var url = 'http://example.com/files?callback=JSON_CALLBACK';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.dir(data);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
bmleite was right, I had to implement this logic on my API.
In my example, my server is made with Silex :
public function index()
{
$callback = $this->request->get('callback');
$files = $this->app['file.manager']->getList();
$response = new \Symfony\Component\HttpFoundation\JsonResponse();
$response->setData($files);
$response->setCallback($callback);
return $response;
}
And it works perfectly now. Thank you.

setMasked(false) not working

In my application i have used the Ext.Viewport.setMasked function, When i call the Processing mask showing properly.But not disabled when it reaches success.Here my code
{
Ext.Viewport.setMasked({
xtype: 'loadmask',
message: 'Processing...',
indicator: true
});
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url: App.gvars.apiurl + 'AddItem', // url : this.getUrl(),
method: "POST",
params: data,
useDefaultXhrHeader: false,
withCredentials: true,
success: function (response) {
var respObj = Ext.JSON.decode(response.responseText);
if(respObj[0].response=="Success"){
Ext.Viewport.setMasked(false);
Ext.Msg.alert("Success", "A new wish has been added To Ur Wish List");
viewgiftlist();
goitems();
}
else{
Ext.Viewport.setMasked(false);
Ext.Msg.alert("Error",respObj[0].errorMsg);
}
},
failure: function (response)
{
Ext.Msg.alert("Error",response.responseText);
}});
}
Please help me to solve the issue
You didnt give setmask(false) in your failure message.. are you getting success response or failure?
The correct usage is in fact Ext.Viewport.setMasked(false);
My guess is that your success conditional isn't working properly. This should be an easy fix for you if you're using console! Fire up Chrome, hit F12 and use your console. Use a console.log after you decode your response, then you can properly debug this.
var respObj = Ext.JSON.decode(response.responseText);
console.log(respObj);
Also, not sure why the success portion of your response would be an array, usually a response looks something like this:
{"success":true,"data":[{"id":"1","first_name":"Test","last_name":"Test"}],"total":1}
Obviously you can craft them how you want, but just looks strange to me. With the above JSON the conditional would be like so:
if(respObj.success) {

Resources