vue.js + Jest : how to test a form post? - vue.js

Until now I gave been using Avoriaz, but I would like to use Jest now ...
found some tuts... but could not get any hint on testing my contact view component sending POST to an external urk...
<form id="contactForm" action="https://formspree.io/mysite.com" method="POST">
<div class="form-group">
<input type="hidden" name="_next" v-model="next" />
<input type="hidden" name="_language" v-model="language" />
<input type="hidden" name="_subject" value="Contact from my site" />
<input v-model="sendername" ...>
<input v-model="email" ...>
</div>
<div class="form-group">
<div class="uk-margin">
<textarea v-model="message" ...></textarea>
</div>
</div>
<button type="submit" class="btn btn-primary btn-gradient submit">Send</button>
</form>
As the external post URL is only valid for production... I would like mock it and use the _next property as a callback page url...
any useful links to put me on first tracks ?? thanks a lot for feedback

You should prevent submit and post data using axios for example and then mock axios.
<!-- the submit event will no longer reload the page -->
<form v-on:submit.prevent="onSubmit"></form>
It's an easier way to unit-test that.

Related

Generating a valid __RequestVerificationToken from C#

One of the most popular books on ASP.NET Core is "Pro ASP.NET Core 3" by Adam Freeman.
In chapters 7-11, he builds an example application, SportsStore.
As you can see, each product in the listing gets its own 'Add To Cart' button:
If we do 'view source' on this page, we'll see the following HTML for that item in the product list:
<div class="card card-outline-primary m-1 p-1">
<div class="bg-faded p-1">
<h4>
Kayak
<span class="badge badge-pill badge-primary" style="float:right">
<small>$275.00</small>
</span>
</h4>
</div>
<form id="1" method="post" action="/Cart">
<input type="hidden" data-val="true" data-val-required="The ID field is required." id="ID" name="ID" value="1" />
<input type="hidden" name="returnUrl" value="/" />
<span class="card-text p-1">
A boat for one person
<button type="submit" class="btn btn-success btn-sm pull-right" style="float:right">
Add To Cart
</button>
</span>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8KKqNOS0gwdMvC0-bdjTwWlvCcBJldeidwIX5b2f24gYblS9X1sqCwJWIEsKKOSf8kut0SQsQRLF3R1XBSYZkPGnta9YzRK4tcQl8dq_0uWmjeUhm8yMe90fWDt_x0smmAD1lmb9-BxQF8y_7-IQSz4" /></form>
</div>
Note the input tag towards the bottom:
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8KKqNOS0gwdMvC0-bdjTwWlvCcBJldeidwIX5b2f24gYblS9X1sqCwJWIEsKKOSf8kut0SQsQRLF3R1XBSYZkPGnta9YzRK4tcQl8dq_0uWmjeUhm8yMe90fWDt_x0smmAD1lmb9-BxQF8y_7-IQSz4" />
If we look at the Views\Shared\ProductSummary.cshtml file in the SportsStore project, we'll see the code that is involved with generating these listing items:
#model Product
<div class="card card-outline-primary m-1 p-1">
<div class="bg-faded p-1">
<h4>
#Model.Name
<span class="badge badge-pill badge-primary" style="float:right">
<small>#Model.Price.ToString("c")</small>
</span>
</h4>
</div>
<form id="#Model.ID" asp-page="/Cart" method="post">
<input type="hidden" asp-for="ID" />
<input type="hidden" name="returnUrl" value="#ViewContext.HttpContext.Request.PathAndQuery()" />
<span class="card-text p-1">
#Model.Description
<button type="submit" class="btn btn-success btn-sm pull-right" style="float:right">
Add To Cart
</button>
</span>
</form>
</div>
As you can see, the form element in this case doesn't have an explicit inclusion of the input tag with the __RequestVerificationToken value. This form thus appears to be a tag helper which takes care of generting the input tag with the __RequestVerificationToken token.
As an experiment, let's suppose I have added the following method to Controllers\HomeController:
[HttpGet]
public ContentResult ButtonExample()
{
var token = "...";
return new ContentResult()
{
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
Content =
String.Format(
#"<!DOCTYPE html>
<html>
<body>
<form id=""1"" method=""post"" action=""/Cart"">
<input type=""hidden"" data-val=""true"" id=""ID"" name=""ID"" value=""1"" />
<button type=""submit"">Add to Cart</button>
</form>
<input name=""__RequestVerificationToken"" type=""hidden"" value=""{0}"" />
</body>
</html>",
token)
};
}
As you can see, this generates a very simple page with a single button which is intended to add the product with ID value 1 (i.e. the Kayak) to the cart.
I of course need to pass an appropriate value for the __RequestVerificationToken.
My question is, is there a way to get this value from C# so that I can include it in the method above?
The idea as shown above would be to set the token value here:
var token = "...";
This is then interpolated into the string that generates the HTML using String.Format.
UPDATE
This page mentions the following:
To generate the anti-XSRF tokens, call the #Html.AntiForgeryToken method from an MVC view or #AntiForgery.GetHtml() from a Razor page.
So I guess the question is, how do we do the equivalent from C# directly instead of from an MVC view or Razor page?
You can add the below code to your form which will generate the __RequestVerificationToken. It is used to prevent CSRF attacks Prevent XSRF/CSRF attacks.
<form action="/" method="post">
#Html.AntiForgeryToken()
</form>

Razor Pages - Run a server side method NOT using post

In Razor pages ASP.NET Core, how do I do a basic onclick event for a button which is of type button?
Do I need to wire up an AJAX GET request to get the below "Resend Code" button to work? There is plenty of chatter about OnPost this and that.. but I don't want to post.
Can't be this hard?
<form method="post">
<div asp-validation-summary="All"></div>
<div class="form-group-item">
<label asp-for="Input.TwoFactorCode"></label>
<input asp-for="Input.TwoFactorCode" class="input" />
<span asp-validation-for="Input.TwoFactorCode"></span>
</div>
<div class="form-group-item">
<label class="margin-0" asp-for="Input.RememberMachine">
<input asp-for="Input.RememberMachine" />
#Html.DisplayNameFor(m => m.Input.RememberMachine)
</label>
</div>
<div>
<button type="button" asp-page-handler="ResendCode" class="btn btn-light">Resend Code</button>
<button type="submit" class="btn btn-secondary">Confirm</button>
</div>
</form>
As it stands, the button won't do anything. You can use JavaScript to intercept the button click and then fire a get request using AJAX (jQuery example below):
$('.btn.btn-light').on('click', function(){
$.get('?handler=ResendCode', data, function(){
...
});
});
You can try changing the button to use formmethod="get":
<button type="submit" formmethod="get" asp-page-handler="ResendCode" class="btn btn-light">Resend Code</button>
Note, this will only work for buttons that have type="submit" or type="image" (other type-values don't cause the form to submit). Also it's an HTML5 attribute.
Reference:
https://html.com/attributes/input-formmethod/
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formmethod
maybe try making your own custom handler methods other than OnPost() and OnGet()

Pug iteration -- express routes

I have a route that returns error messages in express. Using connect-flash. Everything is working fine and I log the messages but I'm unable to display the messages in my pug file. Hopefully someone would direct me to my error/misunderstaning. I follow a tutorial to learn express, so I'll post my code first and then the tutorial code with handlebars.
My route is this:
router.get('/signup', function (req, res) {
var messages = req.flash('error')
console.log(messages)
res.render('signup', { csrfToken: req.csrfToken(), messages: messages, hasErrors : messages.length > 0 });
});
And here is my signup jade file. Notice the if block on top with "each" iteration and then displaying the SINGLE message in P line :
extends layout
block content
//- The error is logged but not displaying in my pug
//- Error iteration to display error messages
if (hasErrors)
each error in hasErrors
p= error
//- end of iteration
div.constainer
div.row
div.col-md-4.offset-4
h1 Signup
form(action="" method="post")
div.form-group
label E-mail:
br
input.form-control( type="text" id="email" name="email")
div.form-group
label Password:
br
input.form-control( type="password" id="password" name="password")
br
input(type="hidden" name = "_csrf" value="#{csrfToken}")
button(type="submit") Signup
The original tutorial has it with handlebars and it works. I'm trying to recreate the same example with pug. Here is the tutorial with handlebars code:
div class="row">
<div class="col-md-4 col-md-offset-4">
<h1>Sign Up</h1>
>>>>>>***{{#if hasErrors}}
<div class="alert alert-danger">
{{# each messages }}
<p>{{this}}</p>
{{/each}}
</div>
>>>>>>{{/if}}***
<form action="/user/signup" method="post">
<div class="form-group">
<label for="email">E-Mail</label>
<input type="text" id="email" name="email" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" class="form-control">
</div>
<input type="hidden" name="_csrf" value="{{ csrfToken }}">
<button type="submit" class="btn btn-primary">Sign Up</button>
</form>
</div>
</div>
The code with handlebars code works. I just translated the same code to pug.
If I remove iteration completely and just add #{hasErrors} Jade display true and false so my route is fine, it is my iteration in Pug.
I'm a beginner. Any help would be appreciated.
As confirmed by OP, the each statement should be each error in messages.

Styling Data Validation Errors with Bootstrap

I am working on an ASP.NET MVC 4 Project. I want to style data validation errors on my login page with Bootstrap 3.0. When I debug the page and it gives data validation errors, this codes are disappeared in source of my login form:
<form action="/Account/Login" class="col-md-4 col-md-offset-4 form-horizontal well" method="post"><input name="__RequestVerificationToken" type="hidden" value="Zbg4kEVwyQf87IWj_L4alhiHBIpoWRCJ9mRWXF6syGH4ehg9idjJCqRrQTMGjONnywMGJhMFmGCQWWvBbMdmGFSUPqXpx6XaS4YfpnbFm8U1" /><div class="validation-summary-errors"><ul><li>The user name or password provided is incorrect.</li>
</ul></div> <div class="form-group control-group">
<div class="col-md-6 col-md-offset-3">
<input class="input-validation-error form-control" data-val="true" data-val-required="User name alanı gereklidir." id="UserName" name="UserName" placeholder="Kullanıcı Adı" type="text" value="" />
<span class="field-validation-error" data-valmsg-for="UserName" data-valmsg-replace="true">User name alanı gereklidir.</span>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-3">
<input class="input-validation-error form-control" data-val="true" data-val-required="Password alanı gereklidir." id="Password" name="Password" placeholder="Şifre" type="password" />
<span class="field-validation-error" data-valmsg-for="Password" data-valmsg-replace="true">Password alanı gereklidir.</span>
</div>
</div>
<div class="form-group">
<div class="col-md-4 col-md-offset-4">
<button class="btn btn-default" type="submit">Giriş Yap</button>
</div>
</div>
</form>
How can I style these errors like "for=inputError" property of label with Bootstrap 3?
As it's shown in Bootstrap's docs, you need to apply class has-error to the div that contains the input and has class form-group:
<div class="form-group has-error">
...
</div>
It's a quite ugly to write a condition for each property you want to check and apply class has-error depending on the results of that condition, though you can do it like so:
<div class="form-group #(Html.ViewData.ModelState.IsValidField(Html.IdFor(x => x.UserName)) ? null : "has-error" )">
This takes care of the server side validation. However, there is also client side validation you need to think about. For that you'd need to write some jQuery that would check for existence of class field-validation-error and apply class has-error depending on the result.
You may do it all your self, though I suggest checking out TwitterBootstrapMVC which does all of that automatically for you. All you'd have to write is:
#Html.Bootstrap().FormGroup().TextBoxFor(m => m.UserName)
Disclaimer: I'm the author of TwitterBootstrapMVC. Using it in Bootstrap 2 is free. For Bootstrap 3 it requires a paid license.

Debug Knockout js variable values within View file

Can I debug the below mentioned code on *.cshtml file ? I have used knockout js as my client side java script library.
<div data-bind="ifnot: book()">
<div>
<h2>Add New Book</h2>
</div>
<div>
<label for="name">Name</label>
<input data-bind="value: $root.Name" type="text" title="Name" />
</div>
<div>
<label for="publisher">Publisher</label>
<input data-bind="value: $root.Publisher" type="text" title="Publisher" />
</div>
<div>
<label for="price">Price</label>
<input data-bind="value: $root.Price" type="text" title="Price" />
</div>
<br />
<div>
<button data-bind="click: $root.create">Save</button>
<button data-bind="click: $root.reset">Reset</button>
</div>
</div>
On above code I need to check the values of say "book() or $root.Name ,etc".Can I do that ?
UPDATE:On Fire bug
You'll need to use client side debugging. Either use a developer toolbar (opened with F12 in most browsers) or use Visual Studio Client Script debugging.
After the #nemesv link I did small R&D about this.Below I have mentioned the way you can find the KO binding values of the DOM elements.Hope this will help someone in future.
Link for the Extension : KnockoutJs Context Debugger
The way you can find the KO Values on DOM elements.