简体   繁体   English

如何使用Nette Tester测试演示者提交的成功表单的响应

[英]How to test response of successful form submit in presenter test with nette tester

I want to test the sign in presenter action with form submit and correct response in redirect. 我想用表单提交测试演示者操作中的登录,并在重定向中更正响应。 Eg I want to test that after correct login, user is redirected somewhere and flash message with text "login successful" is displayed. 例如,我要测试是否正确登录后,将用户重定向到某处,并显示带有“登录成功”文本的Flash消息。

In all the examples the only way to test correct form behavior is to test that I get RedirectResponse (see below). 在所有示例中,测试正确表单行为的唯一方法是测试我是否获得RedirectResponse(请参见下文)。 Isn't that too little? 是不是太少了? How to do the test I describe? 我描述的测试方法如何? Is it even possible? 可能吗

function testSignUpSuccess()
{
    $post = [
        'identity' => 'john.doe@gmail.com',
        'password' => 'superSecret123',
    ];

    $pt = $this->getPresenterTester()
        ->setPresenter('Sign')
        ->setAction('up')
        ->setHandle('signUpForm-submit')
        ->setPost($post);

    $response = $pt->run();

    Assert::true($response instanceof Nette\Application\Responses\RedirectResponse);

    //TODO test that flashMessage: 'login successful' is displayed on final page
}

Note: This example uses PresenterTester tool to get the response but the important part is about working with that response so it doesn't matter whether you get it by native means or by this tool. 注意:此示例使用PresenterTester工具获取响应,但是重要的部分是处理该响应,因此无论是以本机方式还是通过此工具获取响应都无关紧要。

No, it's not posiible, because Nette uses session for storing flash messages. 不,这是不可能的,因为Nette使用会话来存储Flash消息。 You don't have session on console. 您没有在控制台上进行会话。 But you can use Tester\\DomQuery to test if required content is on the page (for example logged in user name). 但是您可以使用Tester\\DomQuery来测试页面上是否包含必需的内容(例如登录的用户名)。

$dom = Tester\DomQuery::fromHtml($html);

Assert::true( $dom->has('form#registration') );
Assert::true( $dom->has('input[name="username"]') );
Assert::true( $dom->has('input[name="password"]') );
Assert::true( $dom->has('input[type="submit"]') );

You will probably need to switch off flash messages in tests to avoid session errors. 您可能需要在测试中关闭Flash消息,以避免会话错误。 You can do it in BasePresenter. 您可以在BasePresenter中进行操作。

abstract class BasePresenter extends Nette\Application\UI\Presenter
{
    /**
     * @var bool
     */
    public $allowFlashMessages = TRUE;

    /**
     * Saves the message to template, that can be displayed after redirect.
     *
     * @param  string
     * @param  string
     *
     * @return \stdClass
     */
    public function flashMessage($message, $type = 'info')
    {
        if ($this->allowFlashMessages) {
            return parent::flashMessage($message, $type);
        }
    }
}

You can then turn it off in you tests. 然后可以在测试中将其关闭。

isset($presenter->allowFlashMessages) && $presenter->allowFlashMessages = FALSE;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM