vuejs / vue-jest Goto Github PK
View Code? Open in Web Editor NEWJest Vue transformer
License: MIT License
Jest Vue transformer
License: MIT License
My project use Babel 7, it seems not work ๐
Any way to force 2 use vue-jest
built in Babel config?
Or provide a way to write custom transformer like babel-jest
does
Plugin 27 specified in "/Users/drake/Projects/bill/node_modules/babel-preset-env/lib/index.js" provided an invalid property of "default" (While processing preset: "/Users/drake/Projects/bill/node_modules/babel-preset-env/lib/index.js")
at Plugin.init (../fin-scripts/node_modules/babel-core/lib/transformation/plugin.js:131:13)
at Function.normalisePlugin (../fin-scripts/node_modules/babel-core/lib/transformation/file/options/option-manager.js:152:12)
at ../fin-scripts/node_modules/babel-core/lib/transformation/file/options/option-manager.js:184:30
at Array.map (<anonymous>)
at Function.normalisePlugins (../fin-scripts/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
at OptionManager.mergeOptions (../fin-scripts/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
at ../fin-scripts/node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:14
at ../fin-scripts/node_modules/babel-core/lib/transformation/file/options/option-manager.js:323:22
at Array.map (<anonymous>)
at OptionManager.resolvePresets (../fin-scripts/node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
const { moduleName } = require('./build/myUtils')
const browsers = {
pc: ['> 1%', 'last 2 versions'],
h5: ['iOS >= 8', 'Android >= 4.4'],
}
module.exports = {
presets: [
[
'env',
{
modules: false,
useBuiltIns: 'usage',
shippedProposals: true,
targets: {
browsers: browsers[moduleName] || browsers.pc,
},
},
],
],
plugins: ['syntax-dynamic-import'],
}
"babel-core": "^7.0.0-beta.2"
"babel-preset-env": "^2.0.0-beta.2"
"vue-jest": "^1.4.0"
As the README states, this lib currently doesn't process the <style>
parts.
That's not a big issue when we unit test components that use the normal styles API, by which I mean they use harcoded class names in the template:
<div class="staticClass" v-bind:class="{ 'dnyamicClass' : someFlag }">
However, for CSS modules, this means that this.$styles
is undefined in unit tests and rendering will fail.
I think we have two options:
$styles
We could simply add this prop to a component if we find a style
part with the modules
attribute, and use a Proxy to return the class that was required:
// pseudocode
this.$style = new Proxy({}, {
get(_, property) {
return property
}
})
Proxies are available in node since http://node.green/#ES2015-built-ins-Proxy, so that's quite good. We are dropping support for node 4.* in vue-cli etc. as well, so that should be enough.
The only downside I see it that we can't catch missing classes: If I mistype a class name in my component, I will still get back that mistyped classname from the proxy. If we properly evaluated the styles, we would get undefined
and could catch this bug better, I think.
We could add the usual popular preprocessors as peer deps, write a small wrapper for each to compile the styles, and then use something like string-extract-class-names to get all classnames from the resulting CSS.
From that, we could build a "real" $styles
object and inject it into the component.
@eddyerburgh - what approach would you prefer?
babel-compiler.js
is currently passing its own lib/
directory to find-babel-config
, which means it always compiles code using jest-vue's .babelrc
and not the project's.
The comments suggest that it should instead be passing the current working directory. I think it would be even better if process.js
passed the path
of the script being compiled to be used.
Originally posted at vuejs-templates/webpack; steps to reproduce the issue are in that post.
Tests were working on Saturday; they started failing last night (PST). JavaScript-only Jest tests without Vue components pass with coverage enabled. Vue tests pass if coverage is disabled.
Note: The setup for this is defect to simply use the vue-cli to install the webpack template and run npm run test
. I'm using Windows 10.
I've isolated an edge case when using css modules and scss generate a Comment
where a HTMLDivElement
is expected.
spec.js
const Constructor = Vue.extend(myComponent); const vm = new Constructor().$mount();
myComponent
This doesn't work
<template lang="pug">
div( :class="$style.box" ) hello
</template>
<style module lang="scss">
.box {
color: red;
}
</style>
This works
<template lang="pug">
div( :class="$style.box" ) hello
</template>
<style module>
.box {
color: red;
}
</style>
I'm almost certain it's something to do with the way babel is set up but can't seem to put my finger on it. The component is being pulled into the test but it's not actually running vue-jest on it, or so it seems.
This is the error
Test suite failed to run
C:/Users/craig.harley/Code/myComponent.vue: Unexpected token (1:0)
> 1 | <template>
.babelrc
{
"presets": ["env"],
"plugins": ["transform-vue-jsx"]
}
relevant package.json:
"devDependencies": {
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-vue-jsx": "^3.5.1",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015": "^6.24.1",
"gulp": "^3.9.1",
"jest": "^22.4.2",
"laravel-elixir": "^6.0.0-17",
"laravel-elixir-vue-2": "^0.3.0",
"laravel-elixir-webpack-official": "^1.0.10",
"node-sass": "^4.5.3",
"vue-jest": "^2.1.0",
"vue-template-compiler": "^2.5.13",
"vue-template-es2015-compiler": "^1.6.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"vue"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
}
}
test looks like this:
import Vue from 'vue';
import Component from './component.vue';
describe('app/components/component', () =>
it('should match the snapshot', () => {
const vm = new Vue({
el: document.createElement('div'),
render: function () {
return (
<Component
name="name"
product="product"
type="type"
/>
)
}
});
return expect(vm.$el).toMatchSnapshot();
}
)
);
Not sure what I'm missing here or if it's a bug with using laraval mix.
Hello,
I try to setup tests with vue-jest
. And there is the following error:
Object spread operator requires specified objectAssign option with 'Object.assign' or polyfill helper.
at Node.transpile (node_modules/vue-template-es2015-compiler/buble.js:12676:11)
In the webpack config there is a buble
property (as explained here: https://github.com/vuejs/vue-loader/blob/master/docs/en/options.md#buble):
test: /\.vue$/,
loader: 'vue-loader',
options: {
buble: {
objectAssign: 'Object.assign',
transforms: {
stripWith: true
}
}
}
Is there a way to pass the same option to Jest?
Thank you
I try to add code coverage to my project, but I use src=
and it doesn't seem to be supported.
Maybe it's related to sourcemaps missing (#29 (comment)).
When using vue-jest as transformer for .vue files istanbul ignore comments like /* istanbul ignore next*/
doesn't take effect on coverage.
Is this currently an option? Currently running into the issue where vue-jest cannot find my .babelrc file when vue-jest's install directory is not within referencing directory.
example:
lerna-repo
-babelrc
-node_modules -> contains-vue jest
-lerna packages
--myComponent
--jestConfiguration
inside my jestConfiguration is a reference to the workspace vue-jest:
transform: {
'.*\.(vue)$': "../node_modules/vue-jest"
}
running the above fails because vue-jest cannot find my babelrc file. however, this works:
example:
lerna-repo
-babelrc
-node_modules -> contains-vue jest
-lerna packages
--myComponent
--jestConfiguration
--babelrc
to get around this, i am linking the parent babelrc file and removing it within npm lifecycle scripts.
version on npm is 5.6.0 and node is 8.9.4
I'm using moduleNameMapper
property on jest.conf.js to define alias to match the same as webpack, jest works when I run entire suite npm run unit
but when I use --watch
flag (or -o
) process hangs with message Determining test suites to run...
. I've discovered that this happens because jest can't resolve alias paths.
I used external template like :
<template
src="vue2-simplert-core/simplert.html">
</template>
Success when building production file using [email protected]
.
But unit test failed to run using [email protected]
Here some snippet of my Jest configuration :
"jest": {
"mapCoverage": true,
"coverageDirectory": "test/coverage",
"moduleNameMapper": {
"^vue$": "vue/dist/vue.common.js"
},
"moduleFileExtensions": [
"js",
"vue"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
}
}
Error that I got is :
ENOENT: no such file or directory, open '~/project/src/vue2-simplert-core/simplert.html'
if I look into error message, it because pointing to my project root folder instead of node_modules
folder.
Is there any missing from my side ?
Thanks for all response ๐
Hello,
I'm looking at adding unit test coverage to my vue app but I'm having trouble fetching my css. I'm currently using external css in my components:
<style module scoped src='./Example.css' />
Which isn't working, I spotted @danielbastos11 's PR adding support for css modules and was wondering if vue-jest can deal with external css yet? If not I'm happy to extend the work in #50 to allow external css files and open a PR for it.
Thanks
Coverage report source lines are not correct.
Clean project created with vue init webpack jest-test
produce faulty sourcecode line references for the coverage report.
I want to configure testing with screenshots for vue components. To prepare a snapshot, I need to select not only HTML but also CSS from the component. How can I do that?
Hi!
Currently I'm trying to code split my vue component with this way:
// App.vue
<style scoped src="./template/style.scss" lang="scss"></style>
<template src="./template/index.html"></template>
<script src="./script/index.js" type="text/javascript"></script>
And it seems that the vue-jest
doesn't render the template. When I mount the component and check the vm.$el.innerHTML
it's empty.
I see the comment in the docs:
https://vue-test-utils.vuejs.org/en/guides/testing-SFCs-with-jest.html
Note: vue-jest currently does not support all the features of vue-loader, for example custom block support and style loading. In addition, some webpack-specific features such as code-splitting are not supported either.
So is the problem I faced is regarding the code splitting not supported yet?
I'm following the guide on Testing SFC with Jest and vue-test-utils. There is note saying:
Note: vue-jest currently does not support all the features of vue-loader, for example custom block support and style loading. In addition, some webpack-specific features such as code-splitting are not supported either.
I'm wondering if there are any plans to include support for the above features. Also, is it even possible to support code-splitting without webpack?
Hi,
I got this warning when installing jest-vue
You are already babel-preset-env
as devDependency
https://github.com/eddyerburgh/jest-vue/blob/f4b55cc60b4795c6ed3215b79cf49d9b928d4945/package.json#L31
But end user is forced to install babel-preset-es2015
https://github.com/eddyerburgh/jest-vue/blob/f4b55cc60b4795c6ed3215b79cf49d9b928d4945/package.json#L54
Is there any reason behind this ?
Thanks.
I'm hitting the following issue when running jest with code coverage:
Running coverage on untested files...Failed to collect coverage from components
/AppFooter.vue
ERROR: Unexpected token u in JSON at position 0
STACK: SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse ()
at compileTypescript (src/node_modules/vue-jest/lib/compilers/typescript-compiler.js:67:44)
at processScript (src/node_modules/vue-jest/lib/process.js:22:12)
at Object.module.exports [as process] (src/node_modules/vue-jest/lib/process.js:71:18)
at ScriptTransformer.transformSource (/node_modules/jest-runtime/build/script_transformer.js:229:35)
at exports.default (/node_modules/jest-cli/build/generate_empty_coverage.js:37:5)
at Object.worker (/node_modules/jest-cli/build/reporters/coverage_worker.js:39:291)
at execMethod (/node_modules/jest-worker/build/child.js:92:29)
at process.on (/node_modules/jest-worker/build/child.js:42:7)
at emitTwo (events.js:126:13)
typescript-compiler.js
is failing JSON.parse
this is the component
<template>
<footer class="page-footer center-on-small-only">
<b-container fluid>
</b-container>
</footer>
</template>
<script lang="ts">
// @ts-ignore
import Component from 'nuxt-class-component'
import Vue from 'vue'
@Component({})
export default class AppFooter extends Vue {
}
Hi,I use the jest to test my component.But I hit a problem.
When I run the unit test I write, the component invoke the instance method will cause an error.
So how should I change my testing code or the implement of the component?
cmpA.vue
export default{
...
methods:{
// the component itself's method
innerCall:function(){
// to invoke the instance/global method
this.Global.test().then(...).catch(...);
}
}
}
cmpA.spec.js
import { shallow } from "vue-test-utils";
import captcha from "@/components/captcha";
describe("cmpA.spec.js",()=>{
const createCmp = propsData => shallow(captcha, {propsData})
let component;
beforeEach(() => {
component = createCmp();
});
it("test the cmpA's innerCall method.", () => {
const stub = jest.fn();
component.setMethods({innerCall: stub});
// just for finish the unit test first
expect(true).toEqual(true);
});
})
If a Vue template contains a stylus that has an import to an external stylus file, the test suite requiring this file fails with the message:
failed to locate @import file path/to/stylus/file/in/vuetemplate
git clone https://github.com/mdvorscak/vue-test-utils-jest-example.git && npm i && npm run test
I am wondering if it would make sense to extract the vue file processing into a separate module, so that other tools could benefit from the existing solution in vue-jest as well. Right now there a several different modules handling the parsed output from vue-template-compiler (vue-jest, vue-loader, vueify or jest-vue-preprocessor).
Background: I am currently working on a project that needs to consume vue files independent from a concrete implementation (like processing via vue-loader or vueify) and came here, because vue-jest does exactly what I would need. But of course vue-jest does not expose the processing functionality, because it serves another purpose.
Does this make sense?
Hello,
I'm working on integrating vue-test-utils
into my existing project which uses jest
and jest-vue-preprocessor
.
The vue-test-utils
docs say to use this jest-vue
package, but I don't understand why I would use one over the other. I'm sure there are significant differences I don't understand.
I'd appreciate any help you can give!
Thanks!
Hi, I've recently attempted moving to vue-jest from jest-vue-preprocessor. However, it seems like there's an issue with the conversion of .vue files that's blocking the coverage reports.
Here's the stack trace:
Failed to write coverage reports:
ERROR: TypeError: Cannot read property 'decl' of undefined
STACK: TypeError: Cannot read property 'decl' of undefined
at path/node_modules/istanbul-reports/lib/lcovonly/index.js:32:38
at Array.forEach (<anonymous>)
at LcovOnlyReport.onDetail (path/node_modules/istanbul-reports/lib/lcovonly/index.js:30:28)
at LcovReport.(anonymous function) [as onDetail] (path/node_modules/istanbul-reports/lib/lcov/index.js:21:24)
at Visitor.(anonymous function) [as onDetail] (path/node_modules/istanbul-lib-report/lib/tree.js:34:30)
at ReportNode.Node.visit (path/node_modules/istanbul-lib-report/lib/tree.js:123:17)
at path/node_modules/istanbul-lib-report/lib/tree.js:116:23
at Array.forEach (<anonymous>)
at visitChildren (path/node_modules/istanbul-lib-report/lib/tree.js:115:32)
at ReportNode.Node.visit (path/node_modules/istanbul-lib-report/lib/tree.js:126:5)
The reason I'm filing this here is because I have no such issues if I use jest-vue-preprocessor instead. Digging through the istanbul code gives me
var fc = node.getFileCoverage()
console.log(fc)
FileCoverage {
data:
{ path: 'unknown',
statementMap:
{ '0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object],
'6': [Object] },
fnMap: {},
branchMap: {},
s:
{ '0': 18,
'1': 20,
'2': 18,
'3': 20,
'4': 15,
'5': 13,
'6': 15,
'7': NaN,
'8': NaN,
'9': NaN,
'10': NaN,
'11': NaN,
'12': NaN,
'13': NaN,
'14': NaN,
'15': NaN,
'16': NaN,
'17': NaN,
'18': NaN,
'19': NaN,
'20': NaN,
'21': NaN,
'22': NaN,
'23': NaN,
'24': NaN,
'25': NaN,
'26': NaN,
'27': NaN },
f:
{ '0': NaN,
'1': NaN,
'2': NaN,
'3': NaN,
'4': NaN,
'5': NaN,
'6': NaN,
'7': NaN,
'8': NaN,
'9': NaN,
'10': NaN,
'11': NaN },
b:
{ '0': [Array],
'1': [Array],
'2': [Array],
'3': [Array],
'4': [Array],
'5': [Array],
'6': [Array],
'7': [Array],
'8': [Array],
'9': [Array],
'10': [Array],
'11': [Array],
'12': [Array],
'13': [Array] },
_coverageSchema: '332fd63041d2c1bcb487cc26dd0d5f7d97098a6c',
hash: 'd3767ca38b776b618c16aa6dc3fa8c1632bfc5e2' } }
Looks to me like the fnMap object is strangely missing. If I mess with the source code to avoid throwing errors, none of my .vue files have coverage reports on them.
Hi,
I'm getting coverage issues with Jest.
When I set mapCoverage: true, some files disapear from the coverage report.
Example:
# mapCoverage:true
src/api | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
linkHeaderParser.js | 100 | 100 | 100 | 100 | |
repositories.js | 100 | 100 | 100 | 100 | |
src/components | 7.84 | 2.94 | 5.88 | 11.76 | |
FileExplorer.vue | 0 | 0 | 0 | 0 |... 51,52,53,54 |
MenuUserRepoList.vue | 0 | 0 | 0 | 0 |... 32,33,34,35 |
Profile.vue | 0 | 0 | 0 | 0 |... 57,58,59,60 |
Readme.vue | 80 | 50 | 50 | 80 | 23 |
# mapCoverage:false
src/api | 92.86 | 84.21 | 100 | 92.86 | |
index.js | 84.62 | 66.67 | 100 | 84.62 | 10,26 |
linkHeaderParser.js | 100 | 100 | 100 | 100 | |
repositories.js | 100 | 100 | 100 | 100 | |
users.js | 100 | 100 | 100 | 100 | |
src/components | 53.4 | 29.73 | 40.74 | 51.61 | |
FileExplorer.vue | 0 | 0 | 0 | 0 |... 51,52,53,54 |
FooterBar.vue | 92.86 | 50 | 100 | 100 | 4,5,6,7 |
MenuNavBar.vue | 100 | 50 | 100 | 100 | 20,21,22 |
MenuUserRepoList.vue | 0 | 0 | 0 | 0 |... 32,33,34,35 |
Profile.vue | 0 | 0 | 0 | 0 |... 57,58,59,60 |
Readme.vue | 94.74 | 57.14 | 80 | 92.86 | 25 |
RepoListItem.vue | 100 | 50 | 66.67 | 100 | 45,46,47 |
(I remove some file for a better readability. See full coverage report (link to travis build):
All sources files are available here: https://github.com/maxpou/gitvub and jest config here
Thank you
Iโve added jest-vue to my project and I realized that the values for the branches coverage are incorrect. I tried the same with your project vue-test-utils-jest-example-master and the issues are the same.
๏ฟผ
You can notice that the template lines are included in the coverage calculation and it also shows 50% of 6 branches coverage when you donโt even have a single branch in the fileโฆ Something is wrong here. Can you look at it?
I made sure I updated vue-jest
and jest
to latest versions with no success.
I have a file structure that looks roughly like this (abstracting the names to simplify)
src
|- components
|- module-A
|- Component1.vue
|- Component2.vue
|- module-B
|- sub-module-C
|- Component3.vue
|- sub-module-D
|- Component4.vue
In this case, all components are SCF .vue
files and Component1.vue
is the only one showing up in coverage. It looks like this
<template>
<div>
...
</div>
</template>
<script>
import Component3 from '../module-B/sub-module-C/Component3';
import Component3 from '../module-B/sub-module-C/Component3';
export default {
components: { Component3, Component3 },
name: 'age',
};
</script>
While the coverage looks like this
-----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------------|----------|----------|----------|----------|-------------------|
All files | 0 | 100 | 100 | 0 | |
Component1.vue | 0 | 100 | 100 | 0 | 8,9 |
-----------------|----------|----------|----------|----------|-------------------|
So, clearly, it's not reading this file correctly for coverage purposes.
This is my jest.conf.js
. It's mostly the normal one generated by vue init
.
module.exports = {
rootDir: __dirname,
moduleFileExtensions: [
'js',
'json',
'vue',
],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
transform: {
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest',
},
testPathIgnorePatterns: [
'<rootDir>/test/e2e',
],
testRegex: 'src/.*\\.spec\\.js$',
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
setupFiles: ['<rootDir>/test/unit/setup'],
mapCoverage: true,
coverageDirectory: '<rootDir>/test/unit/coverage',
collectCoverageFrom: [
'src/**/*.{js,vue}',
'!src/**/*.spec.js',
'!src/main.js',
'!src/router/index.js',
'!**/node_modules/**',
],
};
The only thing strange I'm doing is putting my tests in the same folder as the files they're testing. It's unusual for jest and vue perhaps, but if anything, I'd expect it would give me too much coverage in the report, not too little.
Hi there,
I have some issue to run my tests with component that I import from npm.
I setup a project there where I have the error (did a fork from jest-vue-example)
https://github.com/jeromeky/jest-vue-example
I only added my new dependency inside package.json
"dependencies": { "vue-router": "^2.6.0", "vue-quill-editor": "^2.2.4" },
Then used it inside MessageToggle.vue
import { quillEditor } from 'vue-quill-editor';
export default {
components: { quillEditor },
name: 'message-toggle',
data: () => ({
msg: 'default message'
}),
methods: {
toggleMessage () {
this.msg = this.msg === 'message' ? 'toggled message' : 'message'
}
},
}
But when I running the test, I have this kind of error message :
> [email protected] unit /Users/jerome/git/jest-vue-example
> jest
FAIL src/components/__tests__/MessageToggle.spec.js
โ Test suite failed to run
/Users/jerome/git/jest-vue-example/node_modules/vue-quill-editor/src/editor.vue:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){<template>
^
SyntaxError: Unexpected token <
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:306:17)
at src/components/MessageToggle.vue:8:23
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 2.103s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] unit: `jest`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] unit script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/jerome/.npm/_logs/2017-09-14T07_54_13_778Z-debug.log
Thanks for your help.
Hello!
What do you think about to add a flag to disable all warnings?
Or, for example, a flag to disable only scss
warnings (from scss-compiler.js
)?
I use webpack aliases
in my components and during npm run test
of my project I see to many logs like this.: CSS is not fully supported by vue-jest, so some features will throw errors. Webpack aliases are a common cause of errors.
I've create the following example project: https://github.com/ilyaztsv/vue-jest-warnings
npm i
npm run test 2>&1 | grep 'SCSS is not fully supported'
The example project also related to #69 issue.
If the suggestion suits you then I can create a PR.
Hi!
I configurated jest for testing vue components:
"jest": {
"transform": {
".*.(vue)$": "/node_modules/vue-jest",
But imported nested components are not transformed and I've got a error:
FAIL src/components/card/contacts.test.js
โ Test suite failed to run
/www/spa/node_modules/components/b-button/b-button.vue:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){
^
SyntaxError: Unexpected token <
What am I doing wrong?
PS corresponding to @eddyerburgh 's question - yes I'm importing with .vue extension.
Just a heads up, the changelog does not seem up to date. There's a v 2.0.0 somewhere in the middle and no mention of v2.1.0.
Cheers!
As requested, I bring the issue to this repo.
The problem is that <template functional>
is not passed as a functional template, so I'm unable to test by passing the context object to the mount
from the vue-test-utils.
It seems like there is two lockfiles right now. @eddyerburgh which one is actually supposed to be used? Also, the scripts in the package.json
run as npm, while Circle executes yarn.
A component that imports from an alias with babel-plugin-module-resolver
will fail to resolve in jest. Seems like it's not resolving ./
as the babel cwd, but from the component location.
.babelrc:
{
"plugins": [
["module-resolver", { "alias": { "@": "src/components" } } ]
]
}
src/components/A.vue:
<template>
<p>{{ text }}</p>
</template>
<script>
export default {
data() {
return {
text: 'hi'
}
}
};
</script>
src/components/B.vue:
<template>
<ComponentA />
</template>
<script>
import ComponentA from '@/A.vue';
export default {
components: { ComponentA }
};
</script>
Result:
โ Test suite failed to run
Cannot find module './src/components/A.vue' from 'B.vue'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:191:17)
...
I've got path issues when generating the Jest coverage report: yarn jest --coverage
when switching from Karma to Jest. My lcov report with Karma worked perfectly (i.e. relative paths rather than absolute paths, and no "unknown" entry).
I followed the steps from the vue-test-utils doc
--------------------------------------------------------------------------------|----------|----------|----------|----------|----------------|
All files | 100 | 100 | 100 | 100 | |
root | 100 | 100 | 100 | 100 | |
unknown | 100 | 100 | 100 | 100 | |
root/GOPATH/src/bitbucket.org/username/app/client/src/app | 100 | 100 | 100 | 100 | |
api.js | 100 | 100 | 100 | 100 | |
root/GOPATH/src/bitbucket.org/username/app/client/src/auth | 100 | 100 | 100 | 100 | |
actions.js | 100 | 100 | 100 | 100 | |
mutations.js | 100 | 100 | 100 | 100 | |
store.js | 100 | 100 | 100 | 100 | |
root/GOPATH/src/bitbucket.org/username/app/client/src/projects | 100 | 100 | 100 | 100 | |
mocks.js | 100 | 100 | 100 | 100 | |
--------------------------------------------------------------------------------|----------|----------|----------|----------|----------------|
The unknown
file has the following content on the lcov report:
Path must be a string. Received [Function]
TypeError: Path must be a string. Received [Function]
at assertPath (path.js:28:11)
at Object.resolve (path.js:221:7)
at Object.exports.asAbsolute (C:\GOPATH\src\bitbucket.org\[username]\[app]\client\node_modules\istanbul-lib-source-maps\lib\pathutils.js:12:43)
at Context.sourceFinder (C:\GOPATH\src\bitbucket.org\[username]\[app]\client\node_modules\istanbul-lib-source-maps\lib\map-store.js:97:42)
at Context.getSource (C:\GOPATH\src\bitbucket.org\[username]\[app]\client\node_modules\istanbul-lib-report\lib\context.js:74:17)
at Object.annotateSourceCode (C:\GOPATH\src\bitbucket.org\[username]\[app]\client\node_modules\istanbul-reports\lib\html\annotator.js:172:38)
at HtmlReport.onDetail (C:\GOPATH\src\bitbucket.org\[username]\[app]\client\node_modules\istanbul-reports\lib\html\index.js:217:39)
at LcovReport.(anonymous function) [as onDetail] (C:\GOPATH\src\bitbucket.org\[username]\[app]\client\node_modules\istanbul-reports\lib\lcov\index.js:24:24)
at Visitor.(anonymous function) [as onDetail] (C:\GOPATH\src\bitbucket.org\[username]\[app]\client\node_modules\istanbul-lib-report\lib\tree.js:34:30)
at ReportNode.Node.visit (C:\GOPATH\src\bitbucket.org\[username]\[app]\client\node_modules\istanbul-lib-report\lib\tree.js:123:17)
Here's my package.json
jest config:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
},
"mapCoverage": true,
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1"
},
}
I tested it on Linux and Windows, and have the same results.
My application is generated with the webpack
template from vue-cli
.
https://github.com/eddyerburgh/vue-test-utils-jest-example works well and doesn't display the full path.
Typescript was not using a tsconfig
Original issue - vuejs/vue-test-utils#47
This should be fixed in jest-vue 0.6.0.
I'm building an app with vuejs and testing with jest and running the tests locally works, but on circleci fails with the error
FAIL test/unit/specs/components/ui/MessageUI.spec.js
Test suite failed to run
Configuration error:
Could not locate module @/components/ui/MessageUi (mapped as /home/circleci/repo/src/components/ui/MessageUi)
Please check:
"moduleNameMapper": {
"/^@\/(.*)$/": "/home/circleci/repo/src/$1"
},
"resolver": undefined
is not finding the component with the alias @. ๐
the failing component require:
import Component from '@/components/ui/MessageUi'
in the same folder I have another test, working, with:
import Component from '@/components/ui/TabsUi'
build: #39
repo: poc-cms
test: MessageUI.spec.js#L3
component MessageUI.vue
jest config for the @ alias : jest.conf.js#L11
the closest issue related, on jest: jestjs/jest#1290
I met some strange errors, when upgraded from v1.4.0 to v2.0.0.
It occurs errors about parsing css, looks like this:
FAIL test/App.spec.js
โ Test suite failed to run
undefined:62:6: property missing ':'
at error (node_modules/css/lib/parse/index.js:62:15)
at declaration (node_modules/css/lib/parse/index.js:223:33)
at declarations (node_modules/css/lib/parse/index.js:252:19)
at rule (node_modules/css/lib/parse/index.js:560:21)
at rules (node_modules/css/lib/parse/index.js:117:70)
at stylesheet (node_modules/css/lib/parse/index.js:81:21)
at Object.module.exports [as parse] (node_modules/css/lib/parse/index.js:564:20)
at Function.extractClasses (node_modules/extract-from-css/lib/index.js:14:23)
at processStyle (node_modules/vue-jest/lib/process.js:40:31)
at parts.styles.map.ast (node_modules/vue-jest/lib/process.js:105:24)
Here is a part of App.vue
:
62: ul {
63: @include clearfix;
64: }
I use sass-resources-loader
to set global mixin for SCSS at webpack.config.js
.
I think it caused by not loading the mixin in Jest, but README.md told me 'It does not currently compile the style section'.
This makes me confused.
Incidentally, this error did not occur with v1.4.0.
Is there any good solution?
I have been digging into why many of our well tested components/views are not showing up on coverage reports, and I noticed that if I applied the --no-cache
flag to jest I started getting appropriate coverage numbers. There seems to be an issue with the vue-jest
caching mechanism that may be preventing some from getting appropriate coverage numbers.
We copied our settings from https://github.com/eddyerburgh/vue-test-utils-jest-example
It's not an issue!
Could you express your opinion about https://github.com/vire/jest-vue-preprocessor?
A small list of pros/cons against jest-vue-preprocessor in the README of jest-vue would be certainly useful to me and others.
Currently the following message is displayed in the output every vue component containing scss or sass.
[vue-jest]: scss and sass are not currently compiled by vue-jest.
I think that it can be displayed once at once.
What do you think?
Do you want to request a feature or report a bug?
BUG
What is the current behavior?
Don't work with sintaxe sass
in Vue Component File with style. If I remove the --coverage
or remove children flag, it works. For exemple, class with children class:
<style lang="scss" scoped>
.test{
color: red;
.testChildren{
color: black;
}
}
</style>
Command: jest --config test/unit/jest.conf.js --coverage
Please provide your exact Jest configuration
const path = require('path')
module.exports = {
rootDir: path.resolve(__dirname, '../../'),
moduleFileExtensions: [
'js',
'json',
'vue'
],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1'
},
transform: {
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest'
},
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
setupFiles: ['<rootDir>/test/unit/setup'],
coverageDirectory: '<rootDir>/test/unit/coverage',
collectCoverageFrom: [
'src/**/*.{js,vue}',
'!src/**/*.spec.{js,vue}',
'!**/node_modules/**'
],
};
Run npx envinfo --preset jest
in your project directory and paste the
results here
System:
OS: OS X El Capitan 10.11.6
CPU: x64 Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
Binaries:
Node: 8.9.3
Yarn: 1.3.2
npm: 5.6.0
npmPackages:
jest:
wanted: ^22.1.4
installed: 22.4.2
I am trying out your webpack template to use jest for unit testing in a new little app and am getting this error when running npm run unit
:
FAIL test/unit/specs/App.spec.js
โ Test suite failed to run
TypeError: Cannot read property 'lang' of null
at processScript (node_modules/jest-vue/lib/process.js:13:17)
at Object.module.exports [as process] (node_modules/jest-vue/lib/process.js:27:18)
at Object.<anonymous> (test/unit/specs/App.spec.js:1:114)
I reduced the file to an absolute minimum and I'm still getting the error.
App.spec.js
import App from '@/App'
App.vue
<template>
<div id="app">
</div>
</template>
package.json
...
"jest": "^21.2.0",
"jest-vue": "^0.7.0",
...
This is the offending line in jest-vue/lib/process.js
:
function processScript (scriptPart) {
if (scriptPart.lang === 'typescript' || scriptPart.lang === 'ts') {
Which seems to make sense since I do not define a lang
attribute on my script tags.
Hi @eddyerburgh , I'm trying to use jest-vue
with TypeScript support with Vue . My current setup of various files are as follows:
package.json
Jest Block"jest": {
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$",
"moduleFileExtensions": ["ts", "tsx", "vue", "js", "json", "jsx"],
"verbose": true,
"mapCoverage": true,
"transform": {
"^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js",
".*\\.(vue)$": "<rootDir>/node_modules/jest-vue"
}
}
Also I'm using ts-jest
, jest-vue
in conjunction with "vue-typescript-import-dts": "^3.1.1"
.
tsconfig.json
{
"compilerOptions": {
"jsx": "preserve",
"target": "es5",
"lib": ["dom", "es2015"],
"module": "es2015",
"moduleResolution": "node",
"outDir": "lib",
"isolatedModules": false,
"experimentalDecorators": true,
"declaration": true,
"noImplicitAny": false,
"noImplicitThis": false,
"strictNullChecks": true,
"removeComments": true,
"suppressImplicitAnyIndexErrors": true,
"allowSyntheticDefaultImports": true,
"types": ["vue-typescript-import-dts"]
},
"include": ["./src/**/*"]
}
lang="ts"
and vue-class-component
with vue-property-decorator
packagesI'm getting the error as mentioned in Title,
"SyntaxError: Unexpected token u in JSON at position 0" while using jest-vue
Not sure how to resolve this even after stumbling upon many links for solutions.
Full Stack Trace
> jest --coverage
FAIL __tests__/login.spec.ts
โ Test suite failed to run
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at compileTypescript (node_modules/jest-vue/lib/compilers/typescript-compiler.js:55:44)
at processScript (node_modules/jest-vue/lib/process.js:14:12)
at Object.module.exports [as process] (node_modules/jest-vue/lib/process.js:27:18)
console.info node_modules/vue/dist/vue.runtime.common.js:7751
You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html
Login Spec File
import Vue from 'vue'
import Login from '../src/components/login/Login'
describe('Hello Component', () => {
let $mounted
beforeEach(() => {
$mounted = new Vue(Login).$mount()
})
test('snapshot', () => {
let $html = $mounted.$el.outerHTML
expect($html).toMatchSnapshot()
})
})
Cannot share Login.vue file
Versions
"jest": "^21.2.1",
"jest-vue": "^0.8.1",
"ts-jest": "^21.1.3",
"ts-loader": "^3.0.5",
"typescript": "^2.5.3",
"vue-loader": "^13.3.0",
"vue-template-compiler": "^2.5.2",
"vue-typescript-import-dts": "^3.1.1",
"vue": "^2.5.0",
"vue-class-component": "^6.0.0",
"vue-property-decorator": "^6.0.0",
I'm using webpack official template, but it seems this module doesn't support src tags from SFC.
This doesn't work, the component seems to be totally empty.
<template src=./HelloWorld.html></template>
<style scoped src=./HelloWorld.css></style>
<script lang="ts" src="./HelloWorld.js"></script>
This kind of SFC works well with webpack vue-loader. If I fill the SFC with content of each source, jest can load component as expected.
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>Essential Links</h2>
<ul>
<li><a href="https://vuejs.org" target="_blank">Core Docs</a></li>
<li><a href="https://forum.vuejs.org" target="_blank">Forum</a></li>
<li><a href="https://chat.vuejs.org" target="_blank">Community Chat</a></li>
<li><a href="https://twitter.com/vuejs" target="_blank">Twitter</a></li>
<br>
<li><a href="http://vuejs-templates.github.io/webpack/" target="_blank">Docs for This Template</a></li>
</ul>
<h2>Ecosystem</h2>
<ul>
<li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li>
<li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li>
<li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li>
<li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li>
</ul>
</div>
</template>
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
<script>
export default {
name: 'HelloWorld',
data: function () {
return {
msg: 'Welcome to Your Vue.js App'
};
}
};
</script>
There seems to be a critical bug in 2.2.0 with the introduction of SCSS support. When trying to import a file with:
@import '~@design';
I see the repeated error:
File to import not found or unreadable: src/components/~@design.
Parent style sheet: stdin
at Object.module.exports.renderSync (node_modules/node-sass/lib/index.js:439:16)
at module.exports (node_modules/vue-jest/lib/compilers/scss-compiler.js:28:15)
at processStyleByLang (node_modules/vue-jest/lib/process-style.js:6:82)
at processStyle (node_modules/vue-jest/lib/process-style.js:15:17)
at parts.styles.map.ast (node_modules/vue-jest/lib/process.js:98:11)
at Array.map (<anonymous>)
at Object.module.exports [as process] (node_modules/vue-jest/lib/process.js:93:35)
This causes every test to fail, even ones that don't have anything to do with Vue or SCSS - and even when those tests are run in isolation, oddly. Unfortunately, matching neither @design
nor ~@design
in moduleNameMapper
has seemed to have any effect.
As a side note, seeing as there still seem to be quite a few other issues with CSS support in general, I wonder if trying to compile styles should be an opt-in experimental feature for now.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.