编写可测试的Javascript代码
编写可测试的Javascript代码(1):反模式及其解决方案
An Untestable Authentication FormUsername:
Password:
Submit
Both the username and password are required.
You have successfully authenticated!
This username/password combination is not correct.
There was a problem authenticating the user, please try again later.
// Even if test harness was included in the HTML, Javascript is
// inaccessible to tests
$(function() {
// Pyramid of doom - A mixture of disparate concerns and
// very difficult to test individual parts
$("#authentication_form").on("submit", function(event) {
// Event handler logic is mixed with form handling logic
event.preventDefault();
var username $("#username").val();
var password $("#password").val();
if (username&& password) {
// Without a mock, XHR requests require a functioning
// back end, adding extra dependencies and delay
$.ajax({
type: "POST",
url: "/authenticate_user",
data: {
username: username,
password: password