如何一一运行摩卡测试模块?

时间:2019-06-25 10:14:36

标签: javascript npm mocha puppeteer

我正在实施摩卡测试脚本来登录和注销特定网页,我的目的是使此测试脚本模块化。

实际上我的主要测试脚本如下:

describe('Test is being started for user : ' + 
    currentUserInfo.email , function () {
    it('Login Test', async function () {
        await loginTest(page, currentUserInfo.email, 
    currentUserInfo.password);  
    });

    it('Logout Test', async function () {
        await logoutTest(page);
    });
});

logintest.js如下:

module.exports = function(page, userName, userPass){

    before (async function () {
    });

    after (async function () {
        console.log("Login test is finished");
    })

    describe('Login Test is being started for user : ' + 
userName , function () {
        it('Enter Email', async function () {
            await page.focus('#username_box')
            await page.keyboard.type(userName)
        });

        it('Enter Password', async function () {
            await page.focus('#password_box')
            await page.keyboard.type(userPass)
        });

        it('Click "Login in Here" button', async 
function () {
            await page.click('input[value="Log in 
Here"]'); // With type
            await page.waitForNavigation();     
        });

};

在主测试运行时中,logoutTest函数不会等待完成loginTest。另外,我尝试使用Promise对象,但是在这种情况下,我的脚本不会在LoginTest下运行它。

     module.exports = async function(page, userName, userPass){
  return new Promise(resolve => {
    before (async function () {
    });

    after (async function () {
        console.log("Login test is finished");
        resolve(10);
    })

    describe('Login Test is being started for user : ' + 
userName , function () {
        it('Enter Email', async function () {
            await page.focus('#username_box')
            await page.keyboard.type(userName)
        });

        it('Enter Password', async function () {
            await page.focus('#password_box')
            await page.keyboard.type(userPass)
        });

        it('Click "Login in Here" button', async function () {
            await page.click('input[value="Log in Here"]'); // With type
            await page.waitForNavigation();     
        });
    });
  });
};

谢谢

1 个答案:

答案 0 :(得分:0)

Mocha确实按顺序运行。

您的logintest.js正在导出非异步功能。因此,您的主要测试中的await并未按预期阻塞,退出测试将在logintest.js完成之前开始。

此外,我建议您将logintest.js和loginouttest.js嵌套在describe块内的main.js中。

describe('main', function() {
  describe('login', function() {
    before(...)
    after(...)
    it(...)
    it(...)
  }
  describe('logout', function() {
    before(...)
    after(...)
    it(...)
    it(...)
  }
}