Thursday, 23 January 2020

How test JSX Vue component with Jest

I've following component (I simplified code) :

const Comp = Vue.component('Comp', {
    render (h) {
        // Other stuff ...
        return (<div>
            <div style={style}>
                <div style= />
            </div>
        </div>)
    },
})

export default Comp

I wrote following unit test :

it('should be initialized', () => {
    const addEventListener = spyOn(document, 'addEventListener')

    const { vm } = shallowMount(Comp)

    expect(addEventListener).toHaveBeenCalledWith('dragend', jasmine.any(Function))
    expect(addEventListener).toHaveBeenCalledWith('keypress', jasmine.any(Function))
})

When I run unit tests with Jest, I've an error :

ReferenceError: dom is not defined

> 96 |         return (<div>
    |         ^
97 |             <div style={style}>
98 |                 <div style= />
99 |             </div>

My following babel.config.js file :

module.exports = (api) => {
    return {
        presets : ['@babel/preset-env', '@vue/babel-preset-jsx'],
        plugins : [
            '@babel/plugin-syntax-jsx',
            ['@babel/plugin-transform-react-jsx', { pragma : 'dom' }],
            [
                'module-resolver', {
                    root : ['./'],
                    alias : {
                        '@' : './src',
                        '~' : './examples',
                    },
                },
            ],
        ],
    }
}

And my Jest config file :

module.exports = {
    coverageReporters : ['html'],
    "transform": {
        "^.+\\.[t|j]sx?$": "babel-jest"
    },
    collectCoverageFrom : [
        "src/**/*.{js,jsx}"
    ],
    moduleNameMapper : {
        "\\.(css|less|sass|scss)$": "<rootDir>/tests/__mocks__/styleMock.js"
    },
    moduleFileExtensions : ['js', 'jsx']
}

When I build project with rollup, I've no error, only with jest.

Did i miss something ?



from How test JSX Vue component with Jest

No comments:

Post a Comment