我正在使用SonataAdminBundle和DoctrineORMBundle,假设我有一个帖子/标签关系,其中标签是多对多的帖子。
我正在尝试在Post表单上运行功能测试。标签显示在Post表单中抛出一个小部件,其中Tag表单字段来自另一个请求(Ajax调用),并通过Javascript在Post表单中合并。
很容易依赖Javascript来实现这一点,但涉及到功能测试 在使用WebTestCase类的情况下,我发现很难模拟这样的功能。
假设我正在测试Post的Create动作并在我的测试用例中使用此代码。
public function testCreate() {
$client = static::createClient();
$client2 = static::createClient();
//main request. The Post form
$crawler = $client->request('GET','/route/to/posts/create');
//second request (The Tag form) simulating the request made via Ajax
$crawler2 = $client2->request('GET','/admin/core/append-form-field-element?code=my.bundle.admin.tags);
}
上面代码的问题是,从那里我不知道如何将Tag表单合并到Post表单中,所以这样他们一起提交。 有什么想法吗?
答案 0 :(得分:0)
最后,我找到了如何将这两个请求内容合并在一起。这是我使用的代码:
public function testCreate() {
$client = static::createClient();
$client2 = static::createClient();
//main request. The Post form
$crawler = $client->request('GET','/route/to/posts/create');
//second request (The Tag form) simulating the request made via Ajax
$crawler2 = $client2->request('GET','/admin/core/append-form-field-element?code=my.bundle.admin.tags);
//first request's form. This is where we'll merge the content.
$form = $crawler->selectButton('submitButton')->form();
//let's say we want to merge each input fields from the second request
foreach ($crawler2->filter('input') as $node) {
//we use the Crawler\Form::set method with a new InputFormField instance
//that uses a DOMNode as parameter
$form->set(new InputFormField($node));
}
//now we can test if the form has our merged input field from the ajax call
$this->assertTrue($form->has('tagName'));
}