我有一个写在类中的通用测试用例,可以在整个项目的许多场景中使用。我从测试文件(sample.test.js)调用测试用例,它执行得很好。如果我尝试在套件内使用beforeEach块。它表现为异步,并在beforeEach和测试用例并行执行,最终导致所有测试用例失败。如何克服这个?
test_helper.js
class TestHelper {
/**
* Method to execute content-type validation test case.
* @param {String} uri - Uri to perform.
* @param {String} method - Type of request based on this request has been given.
*/
validateContentType(uri, method) {
if (method == 'post') {
it('REQUEST VALIDATION: should return 415 if request body content type is an text', async () => {
// block of code
}, 20000);
}
else {
it('REQUEST VALIDATION: should return 415 if request body content type is an text', async () => {
// block of code
}, 20000);
}
}
/**
* Method to execute empty-body validation test case.
* @param {String} uri - Uri to perform.
* @param {String} method - Type of request based on this request has been given.
*/
validateEmptyRequestBody(uri, method) {
if (method == 'post') {
it('REQUEST VALIDATION: should return 400 if request body is empty', async () => {
// block of code
}, 20000);
}
else {
it('REQUEST VALIDATION: should return 400 if request body is empty', async () => {
// block of code
}, 20000);
}
}
}
sample.test.js
const { TestHelper } = require('../../../../helper/tests_helper');
const helper = new TestHelper();
const uri = 'someUrl';
let url;
let schema;
describe('PUT Request', () => {
let updateId;
// Preparing the Test Suite
beforeAll(async () => {
const schema = {
key1: 'value1',
key2: 'value2',
};
// create a record in database
updateId = await helper.create(schema);
});
afterAll(async () => {
// clear the record from the db after all the test case executed
await helper.clear(updateId);
});
url = `${uri}/update/${updateId}`;
// calling the test case which is available in test_helper.js
helper.validateContentType(url, 'put');
helper.validateEmptyRequestBody(url,'put');
})