async getDocumentTestCases()

in src/language-tools/typescript.ts [137:236]


  async getDocumentTestCases(
    document: vscode.Uri,
    workspaceRoot: string
  ): Promise<TestFileContents> {
    const basename = path.basename(document.fsPath)
    const matchesRegex = TEST_FILE_REGEX.test(basename)
    if (!matchesRegex) {
      return {
        isTestFile: false,
        testCases: [],
      }
    }

    const fileContents = await vscode.workspace.fs.readFile(document)
    const text = fileContents.toString()
    const lines = text.split('\n')

    const testCases: DocumentTestItem[] = []
    const documentTest: DocumentTestItem = {
      name: path.basename(document.fsPath),
      range: new vscode.Range(0, 0, 0, 0),
      uri: document,
      testFilter: '',
    }

    const describeStack: DocumentTestItem[] = []
    const indentStack: number[] = []

    for (let lineNum = 0; lineNum < lines.length; lineNum++) {
      const line = lines[lineNum]
      const indent = line.search(/\S/)

      if (indent === -1) continue

      while (
        indentStack.length > 0 &&
        indent <= indentStack[indentStack.length - 1]
      ) {
        describeStack.pop()
        indentStack.pop()
      }

      const describeMatch = line.match(/describe\s*\(\s*['"`]([^'"`]+)['"`]/)
      if (describeMatch) {
        const position = new vscode.Position(lineNum, 0)
        const describeName = describeMatch[1]
        const parent =
          describeStack.length > 0
            ? describeStack[describeStack.length - 1]
            : undefined

        const lookupKey = parent?.lookupKey
          ? `${parent.lookupKey} ${describeName}`
          : describeName

        const describeItem: DocumentTestItem = {
          name: describeName,
          range: new vscode.Range(position, position),
          uri: document,
          testFilter: describeName,
          parent: parent,
          lookupKey: lookupKey,
        }
        testCases.push(describeItem)
        describeStack.push(describeItem)
        indentStack.push(indent)
        continue
      }

      const testMatch = line.match(/(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]/)
      if (testMatch) {
        const position = new vscode.Position(lineNum, 0)
        const testName = testMatch[1]
        const parent =
          describeStack.length > 0
            ? describeStack[describeStack.length - 1]
            : undefined

        const lookupKey = parent?.lookupKey
          ? `${parent.lookupKey} ${testName}`
          : testName

        const testItem: DocumentTestItem = {
          name: testName,
          range: new vscode.Range(position, position),
          uri: document,
          testFilter: testName,
          parent: parent,
          lookupKey: lookupKey,
        }
        testCases.push(testItem)
      }
    }

    return {
      isTestFile: true,
      testCases: testCases,
      documentTest: documentTest,
    }
  }