在夹具挂钩中使用用户代理进行浏览器检测
Browser detection using user agent in fixture hooks
我有一些测试只需要在移动浏览器中 运行 即可。目前我有一个客户端功能来检查用户代理。
const checkMobile = ClientFunction(() => /iPhone|Android/i.test(navigator.userAgent))
然后我在我的测试中访问:
test("Check if mobile", async t => {
const isMobile = await checkMobile();
if (isMobile) {
await t
// do the tests
}
}
有没有办法让我在灯具中使用它?就像一个只有 运行 如果 checkMobile
是 true
的装置?所以我不需要在每个测试中手动重复这个检查。我确信有比我现在拥有的更聪明的方法来解决这个问题。我尝试在夹具的 beforeEach
挂钩中进行检查,但我无法尝试在变量中共享结果以传递给测试。
要从夹具挂钩中共享一个变量进行测试,您可以使用fixture context
https://devexpress.github.io/testcafe/documentation/guides/basic-guides/organize-tests.html#share-variables-between-test-hooks-and-test-code
此外,您可以按以下方式重新组织测试:
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
函数,对移动设备进行了额外的检查。
此外,您可以参考此评论 https://github.com/DevExpress/testcafe/issues/1626#issuecomment-417424558 以查看还有哪些其他方法可以解决此问题。
我有一些测试只需要在移动浏览器中 运行 即可。目前我有一个客户端功能来检查用户代理。
const checkMobile = ClientFunction(() => /iPhone|Android/i.test(navigator.userAgent))
然后我在我的测试中访问:
test("Check if mobile", async t => {
const isMobile = await checkMobile();
if (isMobile) {
await t
// do the tests
}
}
有没有办法让我在灯具中使用它?就像一个只有 运行 如果 checkMobile
是 true
的装置?所以我不需要在每个测试中手动重复这个检查。我确信有比我现在拥有的更聪明的方法来解决这个问题。我尝试在夹具的 beforeEach
挂钩中进行检查,但我无法尝试在变量中共享结果以传递给测试。
要从夹具挂钩中共享一个变量进行测试,您可以使用fixture context
https://devexpress.github.io/testcafe/documentation/guides/basic-guides/organize-tests.html#share-variables-between-test-hooks-and-test-code
此外,您可以按以下方式重新组织测试:
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
函数,对移动设备进行了额外的检查。
此外,您可以参考此评论 https://github.com/DevExpress/testcafe/issues/1626#issuecomment-417424558 以查看还有哪些其他方法可以解决此问题。