javascript - Mocha 动态测试生成与动态数据生成
问题描述
我创建了一个名为testLoginFailed
let testloginFailed = (app, title, data) => {
it(title, function (done) {
request(app)
.post(apiEndPoints.auth.login)
.send(data)
.then((response) => {
response.statusCode.should.equal(401);
response.body.error.name.should.equal('Error');
response.body.error.message.should.equal('login failed');
response.body.error.code.should.equal('LOGIN_FAILED');
done();
})
.catch((error) => {
done(error);
});
});
};
这是我的描述块
describe('login negative Tests', () => {
before(function () {
let loginFailedTests = [
{
title: 'it should fail user login using mobile because of incorrect mobile',
data: {
username: '1223334444',
password: options.user.password
}
}, {
title: 'it should fail user login using mobile because of incorrect password',
data: {
username: options.user.mobileNumber,
password: options.user.password + '123'
}
}
];
});
loginFailedTests.forEach((test) => {
testloginFailed(app, test.title, test.data);
});
});
问题陈述:
- 我想使用上述函数“testloginFailed”生成动态测试用例。
- 所以我用不同的测试数据集testloginFailed在循环中调用该方法。
- 数组testloginFailed在 before 块中被初始化,因为它需要使用选项在 glocal 范围内的一些数据。
问题:当我在上面的步骤 2 中尝试使用这个数组testloginFailed时,它说
loginFailedTests.forEach((test) => { ^
ReferenceError: loginFailedTests 未定义
解决方案
来自文档RUN CYCLE OVERVIEW。
- 加载测试文件时,Mocha 会执行其所有套件并在其中找到(但不执行)任何钩子和测试。
- 任何“首先”钩子(对于根套件,这只发生一次;请参阅根钩子插件)
我们知道describe()
和它的回调将在before
钩子之前执行。执行顺序是describe()
=> before()
=>it()
所以你应该把测试数据的初始化过程放在describe()
块中。
例如
const { expect } = require('chai');
const options = { user: { password: '123', mobileNumber: '321' } };
const app = {};
let testloginFailed = (app, title, data) => {
it(title, function () {
expect(1 + 1).to.be.eql(2);
});
};
describe('login negative Tests', () => {
let loginFailedTests = [
{
title: 'it should fail user login using mobile because of incorrect mobile',
data: {
username: '1223334444',
password: options.user.password,
},
},
{
title: 'it should fail user login using mobile because of incorrect password',
data: {
username: options.user.mobileNumber,
password: options.user.password + '123',
},
},
];
loginFailedTests.forEach((test) => {
testloginFailed(app, test.title, test.data);
});
});
测试结果:
login negative Tests
✓ it should fail user login using mobile because of incorrect mobile
✓ it should fail user login using mobile because of incorrect password
2 passing (5ms)
推荐阅读
- node.js - 在“...gistry.npmjs.org/loda”附近解析时 JSON 输入意外结束
- php - Contact-Form 7 重新加载页面而不是执行 AJAX
- google-apps-script - 如何为 4 个多个依赖下拉菜单创建脚本?
- c++ - C++ file.close() 提供了额外的时间
- python-3.x - 转换熊猫时间戳列表
- python - 存在数据间隙时如何在 Plotly 中创建正确填充的线条
- r - 为什么我需要将 data.table 分配给新对象以过滤行?
- ubuntu - 使用 cmake 编译循环时出现问题:找不到 OpenImageIO(缺少:OPENIMAGEIO_LIBRARY OPENIMAGEIO_INCLUDE_DIR)
- sql - MS SQL Server - 重命名表名但不更改所有查询
- jquery - 通过 jQuery 和处理程序使用会话超时