Vue Storybook Jest Addon configuration problem - vue.js

I wonder if someone using the jest addon can share it's Vue Storybook configuration, since I can't seem to make it work. I've tried the global mode:
In Storybook's config.js:
import { withTests } from '#storybook/addon-jest';
import results from '../.jest-test-results.json';
addDecorator(
withTests({
results,
})
);
And inside my Story:
storiesOf('Elements/Tag', module)
.addParameters({ jest: ['ThuleTag'] })
.addDecorator(VueInfoAddon)
.addDecorator(withTests({ results })('ThuleTag'))
.add('Squared',
withNotes(_notes)(() => ({
components: {ThuleTag},
template: _template,
propsDescription: {
size: 'medium / small / mini',
type: 'success / info/warning / danger'
}
})),
)
I get this error:
TypeError: Object(...)(...).addParameters is not a function
I've also tried the local way:
In my Story:
import { storiesOf } from '#storybook/vue'
import { withNotes } from '#storybook/addon-notes'
import results from '../../../jest-test-results.json'
import { withTests } from '#storybook/addon-jest'
import ThuleTag from '../../components/ui/elements/ThuleTag.vue'
let _notes = `A simple wrapper for the Elements el-tag, that accepts the same <i>type</i> and <i>size</i> props`
let _template = `<thule-tag
size="small"
key="name">Tag Namez
</thule-tag>`
storiesOf('Elements/Tag', module)
.addDecorator(withTests({ results }))
.add('Squared',
withNotes(_notes)(() => ({
components: {ThuleTag},
template: _template,
propsDescription: {
size: 'medium / small / mini',
type: 'success / info/warning / danger'
}
})),
{
jest: ['ThuleTag.test.js'],
}
)
Here I get this error:
Error in render: "TypeError: Cannot read property '__esModule' of undefined"
And the Tests tab is shown with this message:
This story has tests configured, but no file was found
Can someone point me what's messing things up please?

It looks like storybook jest addon is not supported for Vue.js for now
https://github.com/storybooks/storybook/blob/master/ADDONS_SUPPORT.md

Ok, about first error
Error in render: "TypeError: Cannot read property '__esModule' of undefined"
I think that you should check your babel-config, It seems like you forget some presets for your framework.
About second question
This story has tests configured, but no file was found
That problem happens from Jest and storybook/addon-jest want to get with equals api, but they can't. In last versions of Jest, output file structure has options.testResults , but storybook/addon-jest wants options.results & options.results.testResults.
There are two possible solutions:
use appropriate version of Jest and storybook/addon-jest
apply huck in index.js of storybook-jest library, smth like that
if (testFiles && !testFiles.disable) {
//todo: HERE should be your storybook hack
options.results = options.tests.testResults;
options.results.testResults = options.results;
emitAddTests({
kind: kind,
story: story,
testFiles: testFiles,
options: options
});
}

Related

How to make a dynamic import in Nuxt?

In my nuxt component I want to use the ace editor:
import Ace from "ace-builds/src-noconflict/ace"
when the component is mounted I am doing the following:
this.editor = Ace.edit...
Obviously the window is not defined on the server on page reload. But unfortunately I just can't find a solution to fix this issue.
Is there a way to import a package on the mounted() hook?
I already tried
const Ace = require("ace-builds/src-noconflict/ace")
But that doesn't quite seem to work. Do you have any ideas to solve this issue?
I already tried to register a plugin plugins/ace.js:
import Vue from "vue"
import Ace from "ace-builds/src-noconflict/ace"
Vue.use(Ace)
registered it in nuxt.config.js:
plugins: [
{ src: "~/plugins/ace", mode: "client" }
],
But how do I use Ace in my component now? It is still undefined...
Since the error was thrown during the import statement, I'd recommended using dynamic imports as explained in my other answer here.
async mounted() {
if (process.client) {
const Ace = await import('ace-builds/src-noconflict/ace')
Ace.edit...
}
},
From the official documentation: https://nuxtjs.org/docs/2.x/internals-glossary/context
EDIT: I'm not sure about Ace and it's maybe a drastic change but you may also give a look to vue-monaco which is elbow-to-elbow popularity wise (vanilla Monaco editor).
EDIT2: mounted actually only runs on the client so you could strip the process.client conditional. Meanwhile, I do let it here in case you want to run some logic in other hooks like created (which are run on both server + client). More info here.
EDIT3: not directly related to the question, but some packages expose a component which is only available on the client-side (no SSR support), in those cases you could import the component only on the client side and easily prevent any other errors.
Nuxt Plugin
IMHO you were on the right track with the "plugin" solution. Only mistake was the
Vue.use(Ace) part. This only works for vue plugins.
The plugin file could look somewhat like that:
import Ace from 'ace-builds/src-noconflict/ace'
import Theme from 'ace-builds/src-noconflict/theme-monokai'
export default ({ app }, inject) => {
inject('ace', {
editor: Ace,
theme: Theme
})
}
Then you could use this plugin and initiate the editor in a component this way:
<template>
<div id="editor">
function foo(items) {
var x = "All this is syntax highlighted";
return x;
}
</div>
</template>
<script>
export default {
data () {
return {
editor: {}
}
},
mounted () {
this.editor = this.$ace.editor.edit('editor')
this.editor.setTheme(this.$ace.theme)
}
}
</script>

Jest snapshots for react native static images throwing warnings

I am trying to write snapshots tests to check if the correct image is being returned. When I just use zero transforms than the result is always '1' which isnt very helpful. I went onto the site and added this to my package.json
"transform": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/jest/fileTransformer.js"
}
and create a file called fileTransformer that looks like this
// fileTransformer.js
const path = require('path');
module.exports = {
process(src, filename, config, options) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
},
};
Now the tests are resulting in useful snapshots which is great, however im not getting warnings in my console that look like this
console.error node_modules/prop-types/checkPropTypes.js:20
Warning: Failed prop type: Invalid prop `source` supplied to `Image`.
in Image
You can take a look at moduleNameMapper configuration
"^[./a-zA-Z0-9$_-]+\\.png$": "<rootDir>/RelativeImageStub.js",
and inside the file you can export a dummy image path
RelativeImageStub.js
export default '/dummy/path/to/dummyImage.png';
You should also be able to mock the result from importing the image:
Component.spec.js
import Component from './Component';
jest.mock('./path/to/the/image.png', () => "dummy/path/image.png");
Component.js
import image from './path/to/the/image.png';
export default function Component() {
return <Image source={image} />;
}
This way you'll also get an error if the specified path does not exists.

Vue/Nuxt: How to define a global method accessible to all components?

I just want to be able to call
{{ globalThing(0) }}
in templates, without needing to define globalThing in each .vue file.
I've tried all manner of plugin configurations (or mixins? not sure if Nuxt uses that terminology.), all to no avail. It seems no matter what I do, globalThing and this.globalThing remain undefined.
In some cases, I can even debug in Chrome and see this this.globalThing is indeed defined... but the code crashes anyway, which I find very hard to explain.
Here is one of my many attempts, this time using a plugin:
nuxt.config.js:
plugins: [
{
src: '~/plugins/global.js',
mode: 'client'
},
],
global.js:
import Vue from 'vue';
Vue.prototype.globalFunction = arg => {
console.log('arg', arg);
return arg;
};
and in the template in the .vue file:
<div>gloabal test {{globalFunction('toto')}}</div>
and... the result:
TypeError
_vm.globalFunction is not a function
Here's a different idea, using Vuex store.
store/index.js:
export const actions = {
globalThing(p) {
return p + ' test';
}
};
.vue file template:
test result: {{test('fafa')}}
.vue file script:
import { mapActions } from 'vuex';
export default {
methods: {
...mapActions({
test: 'globalThing'
}),
}
};
aaaaaaaaand the result is.........
test result: [object Promise]
OK, so at least the method exists this time. I would much prefer not to be forced to do this "import mapActions" dance etc. in each component... but if that's really the only way, whatever.
However, all I get is a Promise, since this call is async. When it completes, the promise does indeed contain the returned value, but that is of no use here, since I need it to be returned from the method.
EDIT
On the client, "this" is undefined, except that..... it isn't! That is to say,
console.log('this', this);
says "undefined", but Chrome's debugger claims that, right after this console log, "this" is exactly what it is supposed to be (the component instance), and so is this.$store!
I'm adding a screenshot here as proof, since I don't even believe my own eyes.
https://nuxtjs.org/guide/plugins/
Nuxt explain this in Inject in $root & context section.
you must inject your global methods to Vue instance and context.
for example we have a hello.js file.
in plugins/hello.js:
export default (context, inject) => {
const hello = (msg) => console.log(`Hello ${msg}!`)
// Inject $hello(msg) in Vue, context and store.
inject('hello', hello)
// For Nuxt <= 2.12, also add 👇
context.$hello = hello
}
and then add this file in nuxt.config.js:
export default {
plugins: ['~/plugins/hello.js']
}
Use Nuxt's inject to get the method available everywhere
export default ({ app }, inject) => {
inject('myInjectedFunction', (string) => console.log('That was easy!', string))
}
Make sure you access that function as $myInjectedFunction (note $)
Make sure you added it in nuxt.config.js plugins section
If all else fails, wrap the function in an object and inject object so you'd have something like $myWrapper.myFunction() in your templates - we use objects injected from plugins all over the place and it works (e.g. in v-if in template, so pretty sure it would work from {{ }} too).
for example, our analytics.js plugin looks more less:
import Vue from 'vue';
const analytics = {
setAnalyticsUsersData(store) {...}
...
}
//this is to help Webstorm with autocomplete
Vue.prototype.$analytics = analytics;
export default ({app}, inject) => {
inject('analytics', analytics);
}
Which is then called as $analytics.setAnalyticsUsersData(...)
P.S. Just noticed something. You have your plugin in client mode. If you're running in universal, you have to make sure that this plugin (and the function) is not used anywhere during SSR. If it's in template, it's likely it actually is used during SSR and thus is undefined. Change your plugin to run in both modes as well.
This would be the approach with Vuex and Nuxt:
// store/index.js
export const state = () => ({
globalThing: ''
})
export const mutations = {
setGlobalThing (state, value) {
state.globalThing = value
}
}
// .vue file script
export default {
created() {
this.$store.commit('setGlobalThing', 'hello')
},
};
// .vue file template
{{ this.$store.state.globalThing }}

Nuxt - define a const once and which can use across all pages

I'm trying to implement Shopify JS SDK in Nuxt
So this is what I did, a plugin
// plugins/shopify.js
import Vue from 'vue'
import 'isomorphic-fetch'
import Shopify from 'shopify-buy'
export default ({ app }, inject) => {
app.shopify = Shopify.buildClient({
domain: 'aaa.myshopify.com',
storefrontAccessToken: 'aaa'
});
}
nuxt config
//nuxt.config.js
plugins : [{ src : '~/plugins/shopify', ssr: false}]
vendor : ['shopify-buy']
index
asyncData ({ app }) {
return app.shopify.product.fetchAll().then((products) => {
// Do something with the products
console.log(products);
return { products : products }
});
}
The result is
TypeError Cannot read property 'product' of undefined
But it works if I removed the asyncData, refresh my page, and add the code back without refreshing.
I believe this has something to do with the lifecycle.
Can anyone please tell me if I'm doing it the right way, or there's other proper way to define such const which can be use across pages, components etc
And if this is the right way, what I did wrong?
Thanks in advance.
My reference are Nuxt guides as well as examples.
I tried google around but can't locate what I need, or maybe I just didn't get the right keywords.
FROM DOCUMENTATION
Nuxt.js lets you create environment variables that will be shared for
the client and server-side.
To do this, you can use the env property:
nuxt.config.js:
module.exports = {
env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
}
}
Then to access it from anywhere, just use it like so:
process.env.baseEnv
For example, in an axios plugin:
import axios from 'axios'
export default axios.create({
baseURL: process.env.baseUrl
})

How to create unit test cases with Vue, Karma, browserify

I am trying to build some unit test cases to my existing Vue project.
I found some documents there but not useful especially for testing on functions such as Watch, Promise and Then.
Is there any specific and detailed guide line on unit testing with Vue and these plugins?
The target vue has defined a function named test.
const vm = new Vue(target).$mount();
vm.test("message");
But the error message is vm.test is not a function
I do not know why I could not use the function defined in the target.vue.
Meanwhile once I use the test function to change some data, the target vue will update the data automatically.
But it seems that Vue.nextTick does not work on this situation.
Could someone help me on this point?
Thank you very much for your help.
Hellocomponent
export default {
name: 'hello',
data () {
return {
msg: 'Welcome to Your Vue.js App',
test: 'Testing'
}
}
}
Hello.spec.js //for testing Hello.vue
describe('Hello', () => {
it('set correct default data', () => {
expect(typeof Hello.data).to.equal('function')
assert.typeOf(Hello.data, 'function')
const defaultdata = Hello.data()
expect(defaultdata.test).to.be.a('string')
expect(defaultdata.test).to.equal('Testing')
})
})
This is test case of Hello component of vue.js which is created automatically when new template is created. This is using Karma+Mocha+Chai.