在灯具挂钩中使用用户代理进行浏览器检测

时间:2018-11-09 02:50:07

标签: automated-tests e2e-testing testcafe

我有一些仅在移动浏览器中需要运行的测试。目前,我具有用于检查用户代理的客户端功能。

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
  }
}

我有办法在治具中使用它吗?就像只有checkMobiletrue时才运行的灯具?因此,我不需要在每个测试中手动重复此检查。我敢肯定,现在有比我现在更聪明的方法了。我尝试在夹具的beforeEach钩子中进行检查,但是对我而言,尝试在变量中共享结果以传递给测试并没有用。

1 个答案:

答案 0 :(得分:3)

要从夹具挂钩共享变量进行测试,可以使用fixture context http://devexpress.github.io/testcafe/documentation/test-api/test-code-structure.html#sharing-variables-between-fixture-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,以查看存在其他解决问题的方法。

相关问题