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

feat: test.each support string template #2337

Merged
merged 8 commits into from Nov 22, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 13 additions & 1 deletion packages/vitest/src/runtime/suite.ts
Expand Up @@ -212,9 +212,21 @@ function createTest(fn: (
)) {
const testFn = fn as any

testFn.each = function<T>(this: { withContext: () => TestAPI }, cases: ReadonlyArray<T>) {
testFn.each = function<T>(this: { withContext: () => TestAPI }, cases: ReadonlyArray<T>, ...args: any[]) {
const test = this.withContext()

// for template string
if (Array.isArray(cases) && args.length) {
const header = cases.join('').trim().replace(/ /g, '').split('\n').map(i => i.split('|'))[0]
cases = []
for (let i = 0; i < Math.floor((args.length) / header.length); i++) {
const oneCase: Record<string, any> = {}
for (let j = 0; j < header.length; j++)
oneCase[header[j]] = args[i * header.length + j] as any
;(cases as any).push(oneCase)
}
}

return (name: string, fn: (...args: T[]) => void, options?: number | TestOptions) => {
const arrayOnlyCases = cases.every(Array.isArray)
cases.forEach((i, idx) => {
Expand Down
5 changes: 5 additions & 0 deletions packages/vitest/src/types/tasks.ts
Expand Up @@ -130,6 +130,11 @@ interface TestEachFunction {
fn: (...args: T[]) => Awaitable<void>,
options?: number | TestOptions,
) => void
(...args: [TemplateStringsArray, ...any]): (
name: string,
fn: (...args: any[]) => Awaitable<void>,
options?: number | TestOptions,
) => void
}

type ChainableTestAPI<ExtraContext = {}> = ChainableFunction<
Expand Down
26 changes: 26 additions & 0 deletions test/core/test/each.test.ts
Expand Up @@ -169,3 +169,29 @@ test.each([
expect(value1).toBeNull()
expect(value2).toBeNull()
})

test.each`
a | b | expected
${1} | ${1} | ${2}
${'a'} | ${'b'} | ${'ab'}
${[]} | ${'b'} | ${'b'}
${{}} | ${'b'} | ${'[object Object]b'}
${{ asd: 1 }} | ${'b'} | ${'[object Object]b'}
`('returns $expected when $a is added $b', ({ a, b, expected }) => {
expect(a + b).toBe(expected)
})

test.each`
a | b | expected
${true} | ${true} | ${true}
`('($a && $b) -> $expected', ({ a, b, expected }) => {
expect(a && b).toBe(expected)
})

test.each`
a | b | expected
${{ val: 1 }} | ${{ val: 2 }}} | ${3}
`('($a && $b) -> $expected', ({ a, b, expected }) => {
expect(a.val + b.val).toBe(expected)
})