woocommerce/tests/e2e/env/src/setup/jest.failure.js

98 lines
2.2 KiB
JavaScript
Raw Normal View History

2021-03-08 19:07:29 +00:00
/** @format */
import {
sendFailedTestScreenshotToSlack,
2021-03-08 23:22:55 +00:00
sendFailedTestMessageToSlack,
} from '../slack';
2021-03-08 19:07:29 +00:00
import { bind } from 'jest-each';
2021-04-14 13:05:03 +00:00
const { takeScreenshotFor } = require( '../../utils' );
2021-03-08 19:07:29 +00:00
/**
* Override the test case method so we can take screenshots of assertion failures.
*
* See: https://github.com/smooth-code/jest-puppeteer/issues/131#issuecomment-469439666
*/
/**
* We need to reference the original version of Jest.
*/
const originalDescribe = global.describe;
const originalIt = global.it;
2021-03-08 23:22:55 +00:00
/**
* A custom describe function that stores the name of the describe block.
* @type {describe}
*/
2021-03-08 19:07:29 +00:00
global.describe = (() => {
const describe = ( blockName, callback ) => {
try {
originalDescribe( blockName, callback );
} catch ( e ) {
throw e;
}
};
const only = ( blockName, callback ) => {
originalDescribe.only( blockName, callback );
};
const skip = ( blockName, callback ) => {
originalDescribe.skip( blockName, callback );
};
describe.each = bind( describe, false );
only.each = bind( only, false );
skip.each = bind( skip, false );
describe.only = only;
describe.skip = skip;
return describe;
})();
2021-03-08 23:22:55 +00:00
/**
* A custom it function that wraps the test function in a callback
* which takes a screenshot on test failure.
*
* @type {function(*=, *=): *}
*/
2021-03-08 19:07:29 +00:00
global.it = (() => {
const test = async ( testName, callback ) => {
const testCallback = async () => screenshotTest( testName, callback );
2021-03-08 19:07:29 +00:00
return originalIt( testName, testCallback );
};
const only = ( testName, callback ) => {
return originalIt.only( testName, callback );
2021-03-08 19:07:29 +00:00
};
const skip = ( testName, callback ) => {
return originalIt.skip( testName, callback );
2021-03-08 19:07:29 +00:00
};
test.each = bind( test, false );
only.each = bind( only, false );
skip.each = bind( skip, false );
test.only = only;
test.skip = skip;
return test;
})();
2021-03-08 23:22:55 +00:00
/**
* Save a screenshot during a test if the test fails.
* @param testName
* @param callback
* @returns {Promise<void>}
*/
const screenshotTest = async ( testName, callback ) => {
2021-03-08 19:07:29 +00:00
try {
await callback();
} catch ( e ) {
2021-04-14 13:05:03 +00:00
const { title, filePath } = await takeScreenshotFor( testName );
await sendFailedTestMessageToSlack( title );
if ( filePath ) {
await sendFailedTestScreenshotToSlack( filePath );
}
2021-03-08 19:07:29 +00:00
throw ( e );
}
};