forked from cypress-io/cypress-example-recipes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
login.hbs
116 lines (104 loc) · 2.55 KB
/
login.hbs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<!DOCTYPE html>
<html>
<head>
<title>Logging In - XHR Web Form - Login</title>
<script type="text/javascript" src="/node_modules/jquery/dist/jquery.js"></script>
<style type="text/css">
body {
padding: 0 10px;
}
#form-wrapper {
padding: 10px 20px;
background-color: #eee;
}
#form-wrapper ul {
list-style-type: none;
}
#form-wrapper li {
margin: 10px 0;
}
.error {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<h2>login.html</h2>
<p>
This example uses an XHR that POSTs username and password to the node server.
</p>
<p>In this recipe we:</p>
<ul>
<li>Test that sessions (cookies) are properly sent</li>
<li>Test form errors</li>
<li>Show how to bypass the UI entirely to speed up your tests</li>
</ul>
<div id="form-wrapper">
<form>
<ul>
<li>
<label>
Username:
<input name="username" />
</label>
</li>
<li>
<label>
Password:
<input name="password" />
</label>
</li>
<li>
<button type="submit">Submit</button>
</li>
</ul>
</form>
<p class="error"></p>
</div>
<script type="text/javascript">
var $username = $("input[name=username]")
var $password = $("input[name=password]")
var $error = $(".error")
window.Login = {
redirect: function(str){
window.location.pathname = str
},
onSuccess: function(data){
var redirect = data.redirect || "/dashboard"
Login.redirect(redirect)
},
onError: function(jqXhr, textStatus, errorThrown){
var status = jqXhr.status
// if we have a validation problem
if(status === 422){
// pluck out the error from the JSON
var json = jqXhr.responseJSON
var text = json && json.error
} else {
// we dont know what went wrong with the server
var text = ["An error occurred:", status, errorThrown].join(" ")
}
// fill it in
$error.text(text)
}
}
$("form").submit(function(e){
// dont actually submit the form
e.preventDefault()
// post some JSON
$.post({
url: "/login",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
username: $username.val(),
password: $password.val()
})
})
.done(Login.onSuccess)
.fail(Login.onError)
})
</script>
</body>
</html>