我正在学习QUnit并且正在使用网上教程。 Unit Testing Javascript in ASP NET MVC
我使用了以下代码,但无论我是否知道测试数据等于正确的数字,测试都会失败。
cshtml文件:
@{Html.EnableUnobtrusiveJavaScript(true);}
@section Scripts {
<script type="text/javascript">
var cityCount = 0;
$(document).ready(function () {
getCountry();
$('#CountriesID').change(function () {
getCity('AU');
});
});
function getCountry() {
var url = '@Url.Content("~/Home/CountryList")/';
$.getJSON(url, function (data) {
var items = [];
items.push("<option>Select a Country</option>");
$.each(data, function (i, country) {
if (country.Value.indexOf("\'") > -1) {
s = country.Value + " " + country.Text;
alert(s + ": Country.Value cannot contain \'")
}
items.push("<option value='" + country.Value + "'>" + country.Text + "</option>");
});
$('#CountriesID').html(items.join());
})
}
function getCity(countryId) {
var url = '@Url.Content("~/Home/CityList")/' + countryId;
$.getJSON(url, function (data) {
var items = [];
var cityCount = 0;
items.push('<option>Select a City</option>');
$.each(data, function (i, city) {
items.push("<option value='" + city.Value + "'>" + city.Text + "</option>");
cityCount++;
});
alert(cityCount);
$('#CitiesID').html(items.join());
});
}
test("Perform Country onchange", function () {
$('#CountriesID').trigger("change");
equals(cityCount, 3, 'The no. of cities should be 3');
});
</script>
}
<h2>Country</h2>
@Html.ActionLink("Home", "Index", "Home")
<div class="container">
<div id="CountriesDivID">
<label for="Countries">Countries</label>
<select id="CountriesID" name="Countries"></select>
</div>
<div id="CitiesDivID" >
<label for="Cities">Cities</label>
<select id="CitiesID" name="Cities"></select>
</div>
</div>
<div class="tests">
<h1 id="qunit-header">QUnit example</h1>
<ol id="qunit-tests"></ol>
</div>
我在GetCity方法中有一个警告,提醒我cityCount的值,这是正在测试的内容。断言它应该等于3。
然而,这是测试的结果。
所以,我的问题是,我做错了什么?
编辑:如果我删除了GetCity的内容并且只设置了citCount = 3,则测试通过。