UNPKG

expect-webdriverio

Version:

WebdriverIO Assertion Library

68 lines (67 loc) 2.47 kB
export class SoftAssertService { static instance; static GLOBAL_TEST_ID = '__global_soft_assert_context__'; failureMap = new Map(); currentTest = null; constructor() { } 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() || SoftAssertService.GLOBAL_TEST_ID; if (!this.failureMap.has(testId)) { this.failureMap.set(testId, []); } 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; } } this.failureMap.get(testId).push({ error, matcherName, location }); } getFailures(testId) { const id = testId || this.getCurrentTestId() || SoftAssertService.GLOBAL_TEST_ID; return this.failureMap.get(id) || []; } clearFailures(testId) { const id = testId || this.getCurrentTestId() || SoftAssertService.GLOBAL_TEST_ID; this.failureMap.delete(id); } assertNoFailures(testId) { const id = testId || this.getCurrentTestId() || SoftAssertService.GLOBAL_TEST_ID; 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; } }