有没有一种简单的方法可以在黄昏测试中模拟HTTP_REFERER
?我正在使用Laravel\Dusk\Browser
并在各个页面上调用visit()
方法。这是使用Selenium驱动程序。
类似下面的setReferer
:
namespace Example\Tests\Browser\Processes\PublicSite;
class SampleBrowser extends Browser {
use MakesAssertions, ProvidesAdditionalBrowserActions, WaitsForElements;
public function __construct(RemoteWebDriver $driver, $resolver = null)
{
parent::__construct($driver, new ElementResolver($driver,
$resolver->prefix ?? 'body'));
}
}
class SampleTestCase extends BrowserTestCase
{
/**
* Test that the deal builder modal shows up.
*/
public function testRefererRendering()
{
$this->browse(function (SampleBrowser $browser) {
$browser
// this is the bit that I want
->setReferer('https://example.org/')
->visit('/')
->waitForLocation('/?came_via=example.org')
->assertCookieValue('came_via', 'example.org');
});
}
}
答案 0 :(得分:4)
黄昏或任何浏览器/硒测试解决方案都没有实现这种功能,而且似乎也从未实现过。
请参见https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/2047
导航到引荐来源网址,然后注入脚本,使页面导航到要测试的页面。
使用代理服务器拦截请求,并将引荐网址设置为您想要的请求
https://github.com/j-bennet/selenium-referer
如果您要测试服务器端代码的行为,则始终可以在不使用浏览器完全模拟客户端的情况下对其进行测试。
例如:
<?php
namespace App\Http\Controllers;
use \Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class HomeController extends Controller
{
public function home(Request $request)
{
$referer = $request->header('Referer');
if ($referer) {
return redirect()->route('home', ['came_via' => $referer]);
}
return view('welcome');
}
}
和TestCase
<?php
namespace Tests\Feature;
use Tests\TestCase;
class RedirectTest extends TestCase
{
/**
* A basic redirect example.
*
* @return void
*/
public function testRedirection()
{
// Normal request
$response = $this->get('/');
$response->assertStatus(200);
// Referer check redirection
$referer = 'http://google.com';
$response = $this->call('GET', '/', [], [], [], ['HTTP_REFERER' => $referer]);
$response->assertRedirect('/?came_via=' . urlencode($referer));
}
}
结果
OK (2 tests, 4 assertions)