Reputation: 7954
How to test an ajax call using phpunit test case ?
Upvotes: 3
Views: 6261
Reputation: 1410
Depending on how your ajax response is generated, this may be easy or more difficult. If you use a controller to generate the response, you can simply call the appropriate function in the unit test and check the returned HTML/XML. For example, if responses are generated by calling functions on a controller object like this:
$htmlResponse = $controller->buildPage($_REQUEST);
then you can unit test the response like this:
$expected = "<html>whatever html you expect</html>";
$test_request = array(...); // parameters to test
$actual = $controller->buildPage($test_request);
$this->assertEquals($expected, $actual);
If your response isn't generated with a function call like that - if your AJAX request is for an actual page with some dynamic content in it, seems like you could do something like this:
$_POST['parameter1'] = "test value"; // stuff whichever request object you're using
// with the values you need
ob_start();
include('ajax_page.php');
$actual = ob_get_clean();
$expected = "<html>expected html as above</html>";
$this->assertEquals($expected, $actual);
PHPUnit also provides the assertTag assertion for testing that generated HTML and XML contains the tags you expect - it can be a little finicky but it's more robust than just echoing out the response and comparing to a string.
Ultimately, all you want to know is that, given a certain input (the request parameters), you get the output you expect (the returned HTML or XML). The fact that it's an AJAX call doesn't fundamentally alter the equation. If you wanted to test that the AJAX requests are being MADE appropriately, you'd want to do that on the client side with JS testing.
Upvotes: 5