expect-webdriverio
Version:
WebdriverIO Assertion Library
77 lines (76 loc) • 2.44 kB
JavaScript
export class SoftAssertService {
constructor() {
this.failureMap = new Map();
this.currentTest = null;
}
static getInstance() {
if (!SoftAssertService.instance) {
SoftAssertService.instance = new SoftAssertService();
}
return SoftAssertService.instance;
}
setCurrentTest(testId, testName, testFile) {
this.currentTest = { id: testId, name: testName, file: testFile };
if (!this.failureMap.has(testId)) {
this.failureMap.set(testId, []);
}
}
clearCurrentTest() {
this.currentTest = null;
}
getCurrentTestId() {
return this.currentTest?.id || null;
}
addFailure(error, matcherName) {
const testId = this.getCurrentTestId();
if (!testId) {
throw error;
}
const stackLines = error.stack?.split('\n') || [];
let location = '';
for (const line of stackLines) {
if (line && !line.includes('expect-webdriverio') && !line.includes('node_modules')) {
location = line.trim();
break;
}
}
const failures = this.failureMap.get(testId) || [];
failures.push({ error, matcherName, location });
this.failureMap.set(testId, failures);
}
getFailures(testId) {
const id = testId || this.getCurrentTestId();
if (!id) {
return [];
}
return this.failureMap.get(id) || [];
}
clearFailures(testId) {
const id = testId || this.getCurrentTestId();
if (id) {
this.failureMap.delete(id);
}
}
assertNoFailures(testId) {
const id = testId || this.getCurrentTestId();
if (!id) {
return;
}
const failures = this.getFailures(id);
if (failures.length === 0) {
return;
}
let message = `${failures.length} soft assertion failure${failures.length > 1 ? 's' : ''}:\n\n`;
failures.forEach((failure, index) => {
message += `${index + 1}) ${failure.matcherName}: ${failure.error.message}\n`;
if (failure.location) {
message += ` at ${failure.location}\n`;
}
message += '\n';
});
this.clearFailures(id);
const error = new Error(message);
error.name = 'SoftAssertionsError';
throw error;
}
}