I need to write the UT cases for the following function
var emailsender=function(email)
var link = "mailto:"+ email;
window.location.href = link;
}
Can anyone give idea on it?
Instead of testing function you provide, you better separate part which generate link with another function which could be easily testable. For example:
var emailsender = function (email) {
var link = generateLink(email);
window.location.href = link;
}
function generateLink(email) {
return "mailto:"+ email;
}
And you would be able unit test the function which actually generates the link. Testing part which assign window.location.href is pointless, since this is means you just testing the browser.
Related
How we can Bypass or Disable MediaFormatters(JSONFormatter is my only formatter) in some Actions of Choice?
public string GetSample()
{
...
return "data1,data2,data3";
}
In Above action for example, I dont actually need JsonFormatter to work.
I Found That HttpResponseMessage orIHttpActionResult let us control response text.
But I dont know If these classes can bypass MediaFormaters or not.
Thanks
If we want to force web api to return plain text, without any content-negotiation(formatting the output using json,xml,...)we can do this
public HttpResponseMessage GetSample()
{
string result = "data1,data2,data3";
var response = new HttpResponseMessage(HttpStatusCode.OK);
response .Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
return response ;
}
This is useful to improve performance because JsonFormatter is not so performant.
I have the following controller:
public class ResetController : Controller
{
//
// GET: /Reset/
private Models.ResetModel rm = new Models.ResetModel();
public ActionResult Index()
{
//Check that this has a query string that is containing in the database
//and has been done in the last 30 mins.
string qString = Request.QueryString["v"].ToString();
//if this is a good querystring
if (rm.CheckQString(qString))
return View();
else
return View("Index", "Home");
}
I now need to create a unit test to ensure that if the Request.QueryString value is found in the database then the appropriate view is returned but I am unable to do so. Here is my attempt at a test to check this:
[TestMethod()]
public void IndexTest()
{
ResetController target = new ResetController();
var request = new Mock<HttpRequestBase>();
request.SetupGet(r => r.QueryString).Returns(HttpUtility.ParseQueryString("?v=0ocIqhOQkrBaCXRO96E4B5HcOCYgMfJYOpRdNU/yIEUmH2szuXXKU51Td6NzRxlk"));
var result = target.Index() as ActionResult;
Assert.IsNotNull(result);
}
Can someone please help me with suggestions to ensure that this controller is fully tested?
Thanks
This is a late answer, but in the event that someone comes along this post in the future... Refer to this post how would I mock a querystring
The goal is to isolate the test so that it does not depend on the QueryString result from the database, but rather a provided value. To do this in Moq use the SetupGet method after creating a Mock Context. Hope this helps someone!
I would suggest you pass the model as a dependency to the controller. Then you can mock it as well in the unit test to isolate your controller logic from the model's CheckQString implementation logic.
I'm not sure though if I understand your problem correctly.
The good case might then look like this. Of course you would need to check if the correct view was returned.
[TestMethod()]
public void IndexTest()
{
const string query = "some query";
Models.ResetModel rm = new Mock<Models.ResetModel>();
rm.Setup(m => m.CheckQString(query)).Returns(true);
ResetController target = new ResetController(rm.Object);
var request = new Mock<HttpRequestBase>();
request.SetupGet(r => r.QueryString).Returns(HttpUtility.ParseQueryString("?v=" + query));
var result = target.Index() as ActionResult;
Assert.IsNotNull(result);
}
I'm trying to load the saved option from server side with knockout, please see below the general idea,
I have the following classes in javascript:
funcion Request() {
this.Id = ko.observable('');
this.Name = ko.observable('');
this.Form = ko.obsevable('');
}
function Form() {
this.Id = ko.observable('');
this.Name = ko.observable('');
}
this is my viewModel
function RequestViewModel() {
var self = this;
self.Request = new Request();
*self.Request.Form = new Form();*
}
I can save the Form without problem, but when I try to load the Form field saved into the database, the binding doesn't function.
If anybody have ever had the same problem, please let me know How can I fix it?
You form is an observable. When setting an observable, you should call it as a method, and set parse the value as a parameter. Something like this:
function RequestViewModel() {
var self = this;
self.Request = new Request();
self.Request.Form(new Form());
}
If you have loaded the form from the database, it should look something like this:
self.Request.Form(myLoadedForm);
The answer by aaberg is correct, but if you're saying you need to load them all at once, I recommend you use the knockout mapping plugin to automate this: http://knockoutjs.com/documentation/plugins-mapping.html
Your call would look something like this:
ViewModel = ko.mapping.fromJS(requestFromServer);
I have the following code:
public ActionResult Index()
{
AdminPreRegUploadModel model = new AdminPreRegUploadModel()
{
SuccessCount = successAddedCount,
FailureCount = failedAddedCount,
AddedFailure = addedFailure,
AddedSuccess = addedSuccess
};
return RedirectToAction("PreRegExceUpload", new { model = model });
}
public ActionResult PreRegExceUpload(AdminPreRegUploadModel model)
{
return View(model);
}
but model is null when I breakpoint on PreRegExcelUpload. Why?
Instead of using the Session object in Evgeny Levin's answer I would suggest to use TempData. See http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications about TempData.
You could also fix this by calling return PreRegExceUpload(model); instead of return RedirectToAction(..) in you Index function.
TempData is just a "smart" wrapper for the Session, under the hood it still acts the same way.
Since it's only 4 fields, i would pass them via querystring.
Always try and avoid session/tempdata where possible, for which in this scenario it certainly is.
Are you sure that's your full code? As it doesn't make sense.
If your POST'ing some data and saving it to the database (for example), usually you redirect to another action passing the unique identifier (which is usually generated after the save), fetch it back from the DB and return the view.
That is much better practice.
If you explain your scenario a bit more, and show the proper code your using, i can help further.
Use session to pass model to method:
public ActionResult Index()
{
AdminPreRegUploadModel model = new AdminPreRegUploadModel()
{
SuccessCount = successAddedCount,
FailureCount = failedAddedCount,
AddedFailure = addedFailure,
AddedSuccess = addedSuccess
};
Session["someKey"] = model;
return RedirectToAction("PreRegExceUpload");
}
public ActionResult PreRegExceUpload()
{
var model = (AdminPreRegUploadModel) Session["someKey"];
Session["someKey"] = null;
return View(model);
}
Method RedirectToAction() can't take non primitive types as parameters, because url parameters is string.
Right now I'm learning about MVC's implementation of Ajax and I'm having trouble getting it to work correctly. Here's what I have:
#Ajax.ActionLink("Click here to get a title", "Yo",
new AjaxOptions { OnSuccess = "alert(\"YES!\")", OnFailure = "alert(\"WHY?!\")" })
And here are the two controller methods:
public PartialViewResult GetThatTitle()
{
var titular = new TitleDataEntity { };
titular.TitleName = "Inception!";
titular.PublishDate = DateTime.Now;
titular.Id = 2;
return PartialView("_testView", titular);
}
public JsonResult Yo()
{
var titular = new TitleDataEntity { };
titular.TitleName = "Inception!";
titular.PublishDate = DateTime.Now;
titular.Id = 2;
if(Request.IsAjaxRequest())
{
return Json(titular);
}
return Json(titular);
}
When I call the function "Yo", the browser gives me the "WHY?!" alert box. But when I call GetThatTitle, it gives me the success alert. Why is it failing when I try and return a Json result?
You need to allow GET requests like this when returning JSON which are disabled by default:
return Json(titular, JsonRequestBehavior.AllowGet);
Also I would strongly recommend you using FireBug. It shows all AJAX requests in its console and you see the requests and responses. If you have used it you would have seen the following:
InvalidOperationException: This
request has been blocked because
sensitive information could be
disclosed to third party web sites
when this is used in a GET request. To
allow GET requests, set
JsonRequestBehavior to AllowGet.]
which would have put you on the right track of course.