Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract test result reporter and add support bitbucket cloud. #55

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ import jest from 'danger-plugin-jest'
jest()
// Custom path
jest({ testResultsJsonPath: path.resolve(__dirname, 'tests/results.json') })

// BitbucketCloud
import jest, { BitbucketCloudReporter } from 'danger-plugin-jest'

jest({ reporter: BitbucketCloudReporter })
```

See [`src/index.ts`](https://github.com/macklinu/danger-plugin-jest/blob/master/src/index.ts) for more details.
Expand Down
27 changes: 27 additions & 0 deletions src/ReporterHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import * as path from 'path'

const ReporterHelper = {
lineOfError: (msg: string, filePath: string): number | null => {
const filename = path.basename(filePath)
const restOfTrace = msg.split(filename, 2)[1]
return restOfTrace ? parseInt(restOfTrace.split(':')[1], 10) : null
},
sanitizeShortErrorMessage: (msg: string): string => {
if (msg.includes('does not match stored snapshot')) {
return 'Snapshot has changed'
}

return msg
.split(' at', 1)[0]
.trim()
.split('\n')
.splice(2)
.join('')
.replace(/\s\s+/g, ' ')
.replace('Received:', ', received:')
.replace('., received', ', received')
.split('Difference:')[0]
},
}

export default ReporterHelper
138 changes: 11 additions & 127 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,39 @@
import * as fs from 'fs'
import * as path from 'path'

import * as stripANSI from 'strip-ansi'
import { IJestTestResults, ITestResultReporter } from './types'

import GithubReporter from './reporters/GithubReporter'
import BitbucketCloudReporter from './reporters/BitbucketCloudReporter'

import { DangerDSLType } from '../node_modules/danger/distribution/dsl/DangerDSL'
import {
IInsideFileTestResults,
IJestTestOldResults,
IJestTestResults,
} from './types'
declare var danger: DangerDSLType
declare function fail(message?: string): void
declare function message(message?: string): void

export interface IPluginConfig {
testResultsJsonPath: string
showSuccessMessage: boolean
reporter?: ITestResultReporter
}

export { GithubReporter, BitbucketCloudReporter }

export default function jest(config: Partial<IPluginConfig> = {}) {
const {
testResultsJsonPath = 'test-results.json',
showSuccessMessage = false,
reporter = GithubReporter,
} = config
try {
const jsonFileContents = fs.readFileSync(testResultsJsonPath, 'utf8')
const jsonResults: IJestTestResults = JSON.parse(jsonFileContents)
if (jsonResults.success) {
jestSuccessFeedback(jsonResults, showSuccessMessage)
reporter.jestSuccessFeedback(jsonResults, showSuccessMessage)
return
}

const isModernFormatResults = jsonResults.testResults[0].testResults
if (isModernFormatResults) {
presentErrorsForNewStyleResults(jsonResults)
reporter.presentErrorsForNewStyleResults(jsonResults)
} else {
presentErrorsForOldStyleResults(jsonResults as any)
reporter.presentErrorsForOldStyleResults(jsonResults as any)
}
} catch (e) {
// tslint:disable-next-line:no-console
Expand All @@ -45,117 +43,3 @@ export default function jest(config: Partial<IPluginConfig> = {}) {
)
}
}

const jestSuccessFeedback = (
jsonResults: IJestTestResults,
showSuccessMessage: boolean
): void => {
if (!showSuccessMessage) {
// tslint:disable-next-line:no-console
console.log(':+1: Jest tests passed')
} else {
message(
`:+1: Jest tests passed: ${jsonResults.numPassedTests}/${jsonResults.numTotalTests} (${jsonResults.numPendingTests} skipped)`
)
}
}

const presentErrorsForOldStyleResults = (jsonResults: IJestTestOldResults) => {
const failing = jsonResults.testResults.filter(tr => tr.status === 'failed')

failing.forEach(results => {
const relativeFilePath = path.relative(process.cwd(), results.name)
const failedAssertions = results.assertionResults.filter(
r => r.status === 'failed'
)
const failMessage = fileToFailString(
relativeFilePath,
failedAssertions as any
)
fail(failMessage)
})
}

const presentErrorsForNewStyleResults = (jsonResults: IJestTestResults) => {
const failing = jsonResults.testResults.filter(tr => tr.numFailingTests > 0)

failing.forEach(results => {
const relativeFilePath = path.relative(process.cwd(), results.testFilePath)
const failedAssertions = results.testResults.filter(
r => r.status === 'failed'
)
const failMessage = fileToFailString(relativeFilePath, failedAssertions)
fail(failMessage)
})
}

// e.g. https://github.com/orta/danger-plugin-jest/blob/master/src/__tests__/fails.test.ts
const linkToTest = (file: string, msg: string, title: string) => {
const line = lineOfError(msg, file)
const githubRoot = danger.github.pr.head.repo.html_url.split(
danger.github.pr.head.repo.owner.login
)[0]
const repo = danger.github.pr.head.repo
const url = `${githubRoot}${repo.full_name}/blob/${
danger.github.pr.head.ref
}/${file}${line ? `#L${line}` : ''}`
return `<a href='${url}'>${title}</a>`
}

const assertionFailString = (
file: string,
status: IInsideFileTestResults
): string => `
<li>
${linkToTest(
file,
status.failureMessages && status.failureMessages[0],
status.title
)}
<br/>
${sanitizeShortErrorMessage(
status.failureMessages && stripANSI(status.failureMessages[0])
)}

<details>
<summary>Full message</summary>
<pre><code>
${status.failureMessages && stripANSI(status.failureMessages.join('\n'))}
</code></pre>
</details>
</li>
<br/>
`

const fileToFailString = (
// tslint:disable-next-line:no-shadowed-variable
path: string,
failedAssertions: IInsideFileTestResults[]
): string => `
<b>🃏 FAIL</b> in ${danger.github.utils.fileLinks([path])}

${failedAssertions.map(a => assertionFailString(path, a)).join('\n\n')}
`

const lineOfError = (msg: string, filePath: string): number | null => {
const filename = path.basename(filePath)
const restOfTrace = msg.split(filename, 2)[1]
return restOfTrace ? parseInt(restOfTrace.split(':')[1], 10) : null
}

const sanitizeShortErrorMessage = (msg: string): string => {
if (msg.includes('does not match stored snapshot')) {
return 'Snapshot has changed'
}

return msg
.split(' at', 1)[0]
.trim()
.split('\n')
.splice(2)
.join('')
.replace(/\s\s+/g, ' ')
.replace('Received:', ', received:')
.replace('., received', ', received')
.split('Difference:')[0]
}
120 changes: 120 additions & 0 deletions src/reporters/BitbucketCloudReporter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import {
ITestResultReporter,
IJestTestOldResults,
IJestTestResults,
IInsideFileTestResults,
} from '../types'

import { DangerDSLType } from '../../node_modules/danger/distribution/dsl/DangerDSL'
import * as path from 'path'
import * as stripANSI from 'strip-ansi'
import ReporterHelper from '../ReporterHelper'

declare var danger: DangerDSLType
declare function fail(message?: string): void
declare function message(message?: string): void
declare function markdown(message?: string): void

const BitbucketCloudReporter: ITestResultReporter = {
jestSuccessFeedback: (
jsonResults: IJestTestResults,
showSuccessMessage: boolean
) => {
if (!showSuccessMessage) {
// tslint:disable-next-line:no-console
console.log(':+1: Jest tests passed')
} else {
message(
`:+1: Jest tests passed: ${jsonResults.numPassedTests}/${jsonResults.numTotalTests} (${jsonResults.numPendingTests} skipped)`
)
}
},
presentErrorsForOldStyleResults: (jsonResults: IJestTestOldResults) => {
initialFailingMessage()
const failing = jsonResults.testResults.filter(tr => tr.status === 'failed')

failing.forEach(results => {
var relativeFilePath = path.relative(process.cwd(), results.name)
var failedAssertions = results.assertionResults.filter(
r => r.status === 'failed'
)
var failMessage = fileToFailString(
relativeFilePath,
failedAssertions as any
)
markdown(failMessage)
})
},
presentErrorsForNewStyleResults: (jsonResults: IJestTestResults) => {
initialFailingMessage()
const failing = jsonResults.testResults.filter(tr => tr.numFailingTests > 0)

failing.forEach(results => {
var relativeFilePath = path.relative(process.cwd(), results.testFilePath)
var failedAssertions = results.testResults.filter(
r => r.status === 'failed'
)
var failMessage = fileToFailString(relativeFilePath, failedAssertions)
markdown(failMessage)
})
},
}

const initialFailingMessage = () => {
fail('[danger-plugin-jest] Found some issues below.')
markdown(
`

#### ❗️[danger-plugin-jest] Error Messages ️❗️
---
`
)
}

const linkToTest = (file: string, msg: string, title: string) => {
var line = ReporterHelper.lineOfError(msg, file)
return `Case: [${title}](https://bitbucket.org/${
danger.bitbucket_cloud.pr.source.repository.full_name
}/src/${danger.bitbucket_cloud.pr.source.commit.hash}/${file}${
line ? `#lines-${line}` : ''
})`
}

const assertionFailString = (
file: string,
status: IInsideFileTestResults
): string => `
${linkToTest(
file,
status.failureMessages && status.failureMessages[0],
status.title
)}


> ${ReporterHelper.sanitizeShortErrorMessage(
status.failureMessages && stripANSI(status.failureMessages[0])
)}


##### Full message
\`\`\`
${status.failureMessages && stripANSI(status.failureMessages.join('\n'))}
\`\`\`
`

const fileToFailString = (
path: string,
failedAssertions: IInsideFileTestResults[]
): string => `
❌ **Fail** in \`${path}\`
${failedAssertions
.map(function(a) {
return assertionFailString(path, a)
})
.join('\n\n')}
---

`

export default BitbucketCloudReporter
Loading