【问题标题】:How can I inject parameters into a TestCafé test?如何将参数注入 TestCafé 测试?
【发布时间】:2020-01-24 07:25:58
【问题描述】:

场景:

我使用 API 运行包装在代码中的 TestCafé 我有一个要参数化的测试,使用不同的动态值进行测试。

问题

Testcafé 不支持向测试发送参数。有没有办法注入价值?

【问题讨论】:

    标签: javascript automated-tests e2e-testing inject testcafe


    【解决方案1】:

    是的,有办法! clientScripts 功能可用于发送参数。该文档写得很好,如何注入脚本。我花了一些时间才弄清楚如何在测试中使用它,所以希望这会让你走上正轨。

    1. 使用参数创建数据对象
    2. 将 JSON 添加到表示函数的小 JS 代码块中
    3. 使用.clientScripts setter 将代码块注入到您的运行器/夹具/测试中
    4. eval 测试中的代码等等瞧!你有参数
    // Create the data object
    let data = {aString: 'Yo!', aNumber: 345}
    
    // Add it to a String value representing a JS function
    const scriptContent = `
      function getParameters() {
        return ${JSON.stringify(data)};
      }`
    
    // Invoke the test runner with the code block as content
    testcafe('localhost').then(cafe => {
        cafe.createRunner()
          .src('mytest.js')
          .clientScripts({ content: scriptContent })
          .run()
          //...and so on...
    })
    
    

    现在,当执行测试时,getParameters 函数存在于页头中。可以使用ClientFunctiont.eval 评估或调用此代码:

    let x = await t.eval( () => getParameters() );
    console.log(x);
    await t.expect(x.aString).eql('Yo!', 'Not Okey, mKay?')
    

    一个完整的答案working example can be found here

    【讨论】:

      【解决方案2】:

      您可以使用process.env 将参数从您的运行脚本传递给TestCafe 测试。

      //test.js
      const createTestCafe = require('testcafe');
      
      (async => {
         process.env.foo = 'bar';
      
         const testcafe = await createTestCafe();
      
         await testcafe
             .createRunner()
             .src('test.js')
             .browsers('chrome')
             .run();
      
         await testcafe.close();
      })()
      
      //test.js
      fixture `Examples`;
      
      test('process.env', async t => {
          console.log(process.env.foo);
      });
      

      【讨论】:

      • 使用process.env表示参数是全局可用的,对吧?
      • 是的,process.env 中存储的值在全球范围内可用。如果要存储某些特定于某些测试的信息,可以使用对象和JSON.stringify/JSON.parse 函数。看看这个要点:gist.github.com/AndreyBelym/431c7c7cc610a6329df12959da235b9b
      • 非常好。正如问题所说,这些测试是以编程方式执行的,并且在我们的案例中非常喜欢封装参数(不会全局泄漏)。
      猜你喜欢
      • 1970-01-01
      • 2020-07-08
      • 2021-06-27
      • 1970-01-01
      • 2020-05-16
      • 2012-04-06
      • 2015-07-19
      • 2014-04-22
      • 2011-09-26
      相关资源
      最近更新 更多