Issue
I want to test a specific controller action in Yii2 framework. This action render view file that use helper yii\helpers\Url:
Url::toRoute('page')
When unit test call this view I have error:
yii\base\InvalidArgumentException: Unable to resolve the relative route: vendor/bin/. No active controller is available.
Test:
<?php
use app\modules\user\controllers\UserController;
class UserControllerTest extends \PHPUnit_Framework_TestCase
{
public function testActionIndex() {
Yii::configure(Yii::$app, [
'components' => [
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\modules\user\models\User',
],
'request' => [
'class' => 'yii\web\Request',
'cookieValidationKey' => 'abc',
],
],
]);
$controller = new UserController('user', Yii::$app);
$result = $controller->run('index', []);
}
}
How can I mock method Url::toRoute in view to avoid this error?
Solution
Url
helper uses Yii::$app->controller
for resolving relative routes. You need to set Yii::$app->controller
before you call your action:
Yii::$app->controller = new UserController('user', Yii::$app);
$result = Yii::$app->controller->run('index', []);
Alternatively you may avoid this problem using absolute routes:
Url::toRoute('/mymodule/mycontroller/page');
Although it is quite impractical, since you will need to repeat the same route in many places.
Answered By - rob006
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.