0

i have a problem with writing tests for my action that gets called by jquery via ajax. i don't know how to catch the data that is being sent back to the view, by the action, so that i could assert if it's correct. my $.ajax(...) script inserts result, echo-ed by the controller, into a textarea element, but in my test script, result is null. failure message:

Failed asserting that null matches expected '...

here's what my test code so far:

$this->getRequest()->setRawBody('some json containing input params im testing');
$this->getRequest()->setMethod('GET');
$this->getRequest->setHeader('HTTP_X_REQUESTED_WITH','XMLHttpRequest');

$this->dispatch('my url');
$result = json_decode($this->getResponse()->getBody(),true);

$expectedResult = 'some string';
$this->assertEquals($expectedResult, $result['targeted element']);
10
  • And what's inside the $result variable? Also consider using Zend_Json::decode() Commented May 18, 2012 at 20:56
  • if im not mistaken, $result should hold the values of all the fields that were set by the controller. in this case that would be textarea which should hold the string generated by the controller. there are some other text and select elements, but i don't care about them in this particular test Commented May 19, 2012 at 10:06
  • What SHOULD be there is irrelevant. THe question is what IS there :) Commented May 19, 2012 at 11:16
  • there is a null hence: Failed asserting that null matches expected '...' :) Commented May 19, 2012 at 15:45
  • 1
    Than there is a problem in your controller :) It does not send any data :) For returning JSON I suggest using $this->_helper->json($data); which will encode data, disable layout and view and set propper headers. Commented May 21, 2012 at 8:52

1 Answer 1

1

The recommendation I write below is how I test and has proven to be much more useful and less error prone:

  1. No "controller" testing.
  2. Inject models and value objects into your services.
  3. Inject services into your controllers.
  4. Test models, value objects, and services.
  5. Use a JavaScript testing framework to test your JS -- There are tons of good options out there that will allow you to mock your Ajax calls.
Sign up to request clarification or add additional context in comments.

2 Comments

i'm still new the unit testing, so i could use a little more details :)
It really has less to do with unit testing and more to do with software design. You should probably research the following topics (google these): dependency injection, service layer, value objects, and mvvm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.