在夹具挂钩中使用用户代理进行浏览器检测 [英] Browser detection using user agent in fixture hooks
问题描述
我有一些仅在移动浏览器中需要运行的测试.目前,我具有用于检查用户代理的客户端功能.
I have a few tests that only need to be run when in a mobile browser. Currently I have a client function to check the user agent.
const checkMobile = ClientFunction(() => /iPhone|Android/i.test(navigator.userAgent))
然后在测试内部进行访问:
Which I then access inside my tests:
test("Check if mobile", async t => {
const isMobile = await checkMobile();
if (isMobile) {
await t
// do the tests
}
}
我有办法在治具中使用它吗?就像只能在checkMobile
是true
的情况下运行的灯具一样?因此,我不需要在每个测试中手动重复此检查.我敢肯定,现在有比我现在更聪明的方法了.我尝试在灯具的beforeEach
钩子中进行检查,但是对我来说,尝试在变量中共享该结果以传递给测试并没有用.
Is there a way for me to use this in a fixture? Like a fixture which will only run if checkMobile
is true
? So I don't need to repeat this check in every test manually. I'm sure there's a smarter way to go about it than what I have right now. I tried doing the check in the fixture's beforeEach
hook but it didn't work out for me to then try to share the outcome of that in a variable to pass down to the tests.
推荐答案
要共享夹具挂钩中的变量以进行测试,可以使用fixture context
To share a variable from the fixture hook for testing, you can use fixture context
http://devexpress.github.io/testcafe/documentation/test-api/test-code-structure.html#sharing-variables-between-fixture-hooks-and-test-code
此外,您可以通过以下方式重新组织测试:
In addition, you can reorganize your test in the following manner:
import { ClientFunction } from 'testcafe';
fixture `test`.page('http://example.com').beforeEach(async t => {
const isMobile = await checkMobile();
t.ctx.isMobile = isMobile;
})
const checkMobile = ClientFunction(() => /iPhone|Android/i.test(navigator.userAgent))
function testAndCheck (testName, testFn) {
const foo = async t => {
if (t.ctx.isMobile)
await testFn(t)
else
throw new Error('not mobile');
}
test(testName, foo);
}
testAndCheck('test1', async t => {
await t.click('h1');
await t.click('div');
await t.click('h1');
})
在这里,我定义了testAndCheck
函数,该函数通过对移动设备的附加检查来扩展test
函数.
Here I define the testAndCheck
function that extends the test
function with an additional check for mobile devices.
此外,您可以参考此评论 https://github. com/DevExpress/testcafe/issues/1626#issuecomment-417424558 ,看看还有哪些其他方法可以解决该问题.
In addition, you can refer to this comment https://github.com/DevExpress/testcafe/issues/1626#issuecomment-417424558 to see which other ways exist to overcome the issue.
这篇关于在夹具挂钩中使用用户代理进行浏览器检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!