Skip to content

Coverage collection fails for functional components when using TypeScript #88

@tlaak

Description

@tlaak

I'm not sure what's the actual origin of this bug, but I'd like to report it anyway in case someone else is having the same issue. Vue forum didn't really give me any answers to this problem, but I found a workaround myself.

When collecting coverage from *.vue files with jest --config test/unit/jest.conf.js --coverage I encountered an error if I had any functional components declared functional using the attribute in the template block. Like this:

File: HelloFunctional.vue

<template functional>
  <div>Hello from functional component!</div>
</template>

Having a file like this will throw an error in the coverage report:

Running coverage on untested files...Failed to collect coverage from /path/to/project/src/HelloFunctional.vue
ERROR: 'import' and 'export' may only appear at the top level (2:0)
STACK: SyntaxError: 'import' and 'export' may only appear at the top level (2:0)
    at Parser.pp$5.raise (/path/to/project/node_modules/babylon/lib/index.js:4454:13)
    at Parser.pp$1.parseStatement (/path/to/project/node_modules/babylon/lib/index.js:1877:16)
    at Parser.parseStatement (/path/to/project/node_modules/babylon/lib/index.js:5910:22)
    at Parser.pp$1.parseBlockBody (/path/to/project/node_modules/babylon/lib/index.js:2268:21)
    at Parser.pp$1.parseBlock (/path/to/project/node_modules/babylon/lib/index.js:2247:8)
    at Parser.pp$3.parseFunctionBody (/path/to/project/node_modules/babylon/lib/index.js:4235:22)
    at Parser.parseFunctionBody (/path/to/project/node_modules/babylon/lib/index.js:5897:20)
    at Parser.pp$1.parseFunction (/path/to/project/node_modules/babylon/lib/index.js:2386:8)
    at Parser.pp$3.parseFunctionExpression (/path/to/project/node_modules/babylon/lib/index.js:3760:17)
    at Parser.pp$3.parseExprAtom (/path/to/project/node_modules/babylon/lib/index.js:3722:19)

Using the standard vue-cli project with ES6 and Babel will not trigger this same error, so it's TypeScript related.

To solve this issue you need to add a script block with functional = true property in your functional component even if your component only renders the template and nothing else (e.g. an SVG spinner like in my case).

This works:

<template>
  <div>Hello from functional component!</div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'

@Component({})
export default class HelloFunctional extends Vue {
  functional = true
}
</script>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions