Reputation: 43
I am a newbie in creating unit tests for JavaScripts. In my unit test I keep on getting "AssertError: expected "ok" but was [undefined] " as a result. Can any teach me how to do a unit test for ajax calls? Thanks. By the way, I'm using JsTestDriver for testing my unit tests.
Here's my source file:
function getReport(m, y)
{
$.ajax({
url: "url/to",
data: {
m:m,
y:y
},
dataType: 'json',
success:function (res) {
return res;
}
});
}
Here's my test file:
TestCase("Report", {
"test get report": function () {
assertEquals("ok", getReport(1, 2015));
}
});
Upvotes: 4
Views: 7475
Reputation: 561
Before we go further with your question let me ask mine: why do you need to test Ajax requests? Generally, with unit tests you don't test vendor code and functionality such as 3rd party functions, APIs, network issues, database etc. Focus on unit testing the code your team and you created. Let vendor test their code. In this particular example, jQuery Ajax should be tested by jQuery provider, not you.
There is another reason why you shouldn't test Ajax: the test will transfer from unit to integration test because you test that backend returns the correct value from server. That being said, you test how client+server code work together.
The right way to go is to isolate your unit test from external calls by using mocks, spy or stubs. If you are unsure what they are - search in the Internet. All the popular unit testing frameworks and libraries support and provide the easy way to use them.
You might want to test it anyway, for this purpose visit a related post: Unit testing AJAX requests with QUnit
Good luck with unit tests!
Upvotes: 4