0

我正在使用 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 表单中,所以这样它们会一起提交。有任何想法吗?

4

1 回答 1

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'));
}
于 2012-09-24T13:38:41.580 回答