我在为jQuery通过Ajax调用的操作编写测试时遇到问题。 我不知道如何捕获通过操作发送回视图的数据,以便我可以断言它是否正确。 我的 $.ajax(...( 脚本将结果插入到文本区域元素中,由控制器回显, 但是在我的测试脚本中,结果为空。失败消息:
Failed asserting that null matches expected '...
这是我到目前为止的测试代码:
$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']);
我在下面写的建议是我测试的方式,并且已被证明更有用且更不容易出错:
- 没有"控制器"测试。
- 将模型和值对象注入服务。 将
- 服务注入控制器。
- 测试模型、值对象和服务。
- 使用
JavaScript testing framework
来测试你的 JS - 有很多好的选择可以让你模拟你的Ajax调用。