|
| 1 | +const axios = require('axios') |
| 2 | + |
| 3 | +const BS_USER = process.env.BS_USER |
| 4 | +const BS_KEY = process.env.BS_KEY |
| 5 | + |
| 6 | +function getKey (client) { |
| 7 | + // const { capabilities, currentTest } = client |
| 8 | + // originally i wanted to use this but it turns out the information changes |
| 9 | + // on the afterEach, making the key non valid. But because every environment |
| 10 | + // runs on a different thread, the sessionMap object is only shared for a given |
| 11 | + // environment, so only using the name of the test (currentTest.module) seems to be |
| 12 | + // enough |
| 13 | + // return `${capabilities.platform}::${capabilities.browserName}@${ |
| 14 | + // capabilities.version |
| 15 | + // } ${currentTest.module}: ${currentTest.name}` |
| 16 | + |
| 17 | + return `${client.currentTest.module}: ${client.currentTest.name}` |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Generates an object with beforeEach and afterEach functions to be added |
| 22 | + * to every test suite. It cannot be added globably because these must be |
| 23 | + * executed before each test (instead of each test suite as it does in globalModules) |
| 24 | + */ |
| 25 | +module.exports = function sendStatus () { |
| 26 | + const sessionMap = Object.create(null) |
| 27 | + |
| 28 | + return { |
| 29 | + beforeEach (browser, cb) { |
| 30 | + // retrieve the session and save it to the map |
| 31 | + const key = getKey(this.client) |
| 32 | + browser.session(({ sessionId }) => { |
| 33 | + sessionMap[key] = sessionId |
| 34 | + cb() |
| 35 | + }) |
| 36 | + }, |
| 37 | + |
| 38 | + afterEach (browser, cb) { |
| 39 | + const key = getKey(this.client) |
| 40 | + const { results } = this.client.currentTest |
| 41 | + const sessionId = sessionMap[key] |
| 42 | + |
| 43 | + if (!sessionId) { |
| 44 | + console.warn('❌ Cannot find sessionId for ' + key) |
| 45 | + return cb() |
| 46 | + } |
| 47 | + |
| 48 | + if (results.errors > 0) { |
| 49 | + const reason = results.lastError.message |
| 50 | + console.log('Found failed test', reason) |
| 51 | + axios |
| 52 | + .put( |
| 53 | + `https://api.browserstack.com/automate/sessions/${sessionId}.json`, |
| 54 | + { |
| 55 | + // change the name so it's easier to find |
| 56 | + name: key, |
| 57 | + status: 'failed', |
| 58 | + reason |
| 59 | + }, |
| 60 | + { |
| 61 | + auth: { |
| 62 | + username: BS_USER, |
| 63 | + password: BS_KEY |
| 64 | + } |
| 65 | + } |
| 66 | + ) |
| 67 | + .catch(err => { |
| 68 | + console.log('❌ Failed changing status for sessions', err) |
| 69 | + }) |
| 70 | + .then(() => { |
| 71 | + console.log('✅ Sent for', sessionId) |
| 72 | + cb() |
| 73 | + }) |
| 74 | + } else { |
| 75 | + cb() |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments