[英]How can I correctly add a cookie using selenium-webdriver?
I'm trying to write bare bones unit tests using selenium-webdriver
. 我正在尝试使用selenium-webdriver
编写裸露的单元测试。 In order to correctly test my application, I need to prepare each test case with a cookie. 为了正确测试我的应用程序,我需要为每个测试用例准备一个cookie。
I am trying to do the following: 我正在尝试执行以下操作:
it('should set cookies', async function() {
const driver = new webdriver.Builder().forBrowser('chrome').build();
driver.manage().window().setSize(800, 600);
await driver.manage().addCookie({
name: 'KEY',
value: 'COOKIE-VALUE',
domain: '.my.domain',
path: '/',
secure: false
});
await driver.get('http://test.my.domain');
// test following....
});
My tests run (ie calling addCookie
does not throw/reject), but the set cookie values will not be used when the browser makes a request against my application. 我的测试正在运行(即,调用addCookie
不会抛出/拒绝),但是当浏览器向我的应用程序发出请求时,不会使用设置的cookie值。
When I try to log the set cookies like: 当我尝试记录设置的cookie时,例如:
await driver.manage().addCookie({
name: 'KEY',
value: 'COOKIE-VALUE',
domain: '.my.domain',
path: '/',
secure: false
});
const set = await driver.manage().getCookies();
console.log('set', set);
it will tell me that no cookies have been set: 它会告诉我没有设置cookie:
set []
I also dug into the sources of selenium-webdriver
and able to use the debugger to find out that the correct cookie string will be constructed and enqueued here . 我还研究了selenium-webdriver
的源代码,并且能够使用调试器来找出正确的cookie字符串,并将其放入此处 。
How do I correctly add a cookie so that it will be used by the driver instance? 如何正确添加cookie,以便驱动程序实例可以使用它?
For those wondering about async/await
, I have disabled the managed promises using: 对于那些想知道async/await
,我使用以下命令禁用了托管承诺:
webdriver.promise.USE_PROMISE_MANAGER = false;
The method addCookie
add a cookie to the current domain, so you'll first have to navigate to the targeted URL to set the domain: 方法addCookie
将cookie添加到当前域,因此您首先必须导航到目标URL来设置域:
await driver.get('http://test.my.domain');
await driver.manage().addCookie({
name: 'KEY',
value: 'COOKIE-VALUE',
domain: 'test.my.domain',
path: '/',
secure: false
});
https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.