How do I pass variable data between tests

浪子不回头ぞ 提交于 2021-01-27 13:21:31

问题


I am trying to do something similar to this post on TestCafe

I am generating a random email in my helper.js file. I would like to use this random email to log in the test.js file.

This is how I am creating my email in the helper.js

var randomemail = 'test+' + Math.floor(Math.random() * 10000) + '@gmail.com'

This is how I want to use it in my test.js file

.typeText(page.emailInput, randomemail)

I have tried several things without luck. How could I go about using the generated email in my test.js file?


回答1:


Two options:

1) Use the Fixture Context Object (ctx)

fixture(`RANDOM EMAIL TESTS`)
    .before(async ctx => {
        /** Do this to initialize the random email and if you only want one random email 
         *  for the entire fixture */

        ctx.randomEmail = `test+${Math.floor(Math.random() * 1000)}@gmail.com`;
    })
    .beforeEach(async t => {
        // Do this if you want to update the email between each test

        t.fixtureCtx.randomEmail = `test+${Math.floor(Math.random() * 1000)}@gmail.com`;
    })

test('Display First Email', async t => {
    console.log(t.fixtureCtx.randomEmail);
})

test('Display Second Email', async t => {
    console.log(t.fixtureCtx.randomEmail);
})

2) Declare a variable outside of the fixture

let randomEmail = '';

fixture(`RANDOM EMAIL TESTS`)
    .beforeEach(async t => {
        // Do this if you want to update the email between each test

        randomEmail = `test+${Math.floor(Math.random() * 1000)}@gmail.com`;
    })

test('Display First Email', async t => {
    console.log(randomEmail);
})

test('Display Second Email', async t => {
    console.log(randomEmail);
})


来源:https://stackoverflow.com/questions/51488794/how-do-i-pass-variable-data-between-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!