File size: 2,325 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/* global jest */
jest.autoMockOff()
const fs = require('fs')
const path = require('path')
const { defineTest, defineInlineTest, runInlineTest } = require('jscodeshift/dist/testUtils')
const { readdirSync } = require('fs')
const { join } = require('path')

const possibleExtensions = ['ts', 'tsx', 'js', 'jsx']

function getSourceByInputPath(inputPath) {
  let source = ''
  let filePath
  for (const ext of possibleExtensions) {
    const currentPath = `${inputPath}.${ext}`
    if (fs.existsSync(currentPath)) {
      filePath = currentPath
      source = fs.readFileSync(`${inputPath}.${ext}`, 'utf8')
      break
    }
  }
  return [filePath, source]
}

const testFileRegex = /\.input\.(j|t)sx?$/

const fixtureDir = 'next-async-request-api-dynamic-apis'
const transformName = 'next-async-request-api'
const fixtureDirPath = join(__dirname, '..', '__testfixtures__', fixtureDir)
const fixtures = readdirSync(fixtureDirPath)
  .filter(file => testFileRegex.test(file))

describe('next-async-request-api - dynamic-apis', () => {
  for (const file of fixtures) {
    const isTsx = file.endsWith('.tsx')
    const fixture = file.replace(testFileRegex, '')
    const prefix = `${fixtureDir}/${fixture}`;
    const [inputPath, input] = getSourceByInputPath(path.join(`${__dirname}`, `../__testfixtures__/${prefix}.input`))
    const [outputPath, expectedOutput] = getSourceByInputPath(path.join(`${__dirname}`, `../__testfixtures__/${prefix}.output`))
    const extension = path.extname(inputPath)

    const transformPath = `${__dirname}/../${transformName}`
    const transform = require(transformPath).default

    // Override test fixture input filename with `page.tsx` to always match the expected output,
    // otherwise fallback to the original filename.
    const overrideFilename = /[\\/]origin-name-\d{2}-/.test(inputPath) 
      // extract the <name> from `origin-name-<name>-<number>.input.js`
      ? inputPath
        .replace(/origin-name-(\d{2})-/, '')
        .replace(/\.input\./, '.')
      : 'page' + extension

    it(`transforms correctly ${prefix}`, () => {
      runInlineTest(
        transform,
        null,
        {
          path: overrideFilename,
          source: input,
        },
        expectedOutput, 
        {
          parser: isTsx ? 'tsx' : 'babel',
        },
      )
    })
  }
})