Vue-test-utils: Declare/mock a variable before a import

Created on 19 Dec 2018  路  1Comment  路  Source: vuejs/vue-test-utils

Version

1.0.0-beta.27

What is expected?

I have a global var which is defined in my html file :

<script type="text/javascript"> 
var dataLayout = {
            base_url : "http://localhost:8008",
            web_url  : "/",
            locale : "fr"
        }
</script>

When I execute "npm run dev", this var is use in my Axios file to param many values.

import Vue from 'vue'
const base_url = dataLayout.base_url /****** Here ******/

export default {
    get(url, {params, data, headers}, success){
        return  Vue.axios({
                method: 'get',
                url: base_url + url,
                params,
                data,
                headers
            }).then(response => {
                return success(response.data)
        });
    },
}

So in test environment I suppose what I should mock this variable.

What is actually happening?

When I execute "run npm test", I have this error "dataLayout is not defined".

I have already try to define this property inside my test files like :

import { expect } from 'chai'
import {config}  from '@vue/test-utils'

dataLayout = {...}
// or
global.dataLayout = {...}
// or
windows.dataLayout = {...}
// or 
config.mocks['dataLayout'] = {
    base_url : "http://localhost:8008/",
    web_url : '/',
    locale: 'fr',
}
import { mutations } from '../../../store/modules/global' /****** Modules global use the Axios file *****/

describe('mutations', () => {
    beforeEach(() => { mock(dataLayout); });
    it('Load global (change curreny et url)', () => {
        // mock state
        const state = { count: 0 }
        // apply mutation
        mutations.GLOBAL_LOAD(state, {currency: 'eur', url_magento_project:'url_magento_project'})

        // assert result
        expect(state.currency).to.equal('eur')
        expect(state.url_magento_project).to.equal('url_magento_project')

    })
})

But I have always the same error, please help !

question

Most helpful comment

This is because the file that accesses the property on dataLayout is evaluated before your test runs.

If you're using mocha, create a setup.js file, and use the mocha require option to require the file before any other files are required:

mocha --require setup.js
// setup.js

global.dataLayout = {}

With Jest, use setupFiles.

>All comments

This is because the file that accesses the property on dataLayout is evaluated before your test runs.

If you're using mocha, create a setup.js file, and use the mocha require option to require the file before any other files are required:

mocha --require setup.js
// setup.js

global.dataLayout = {}

With Jest, use setupFiles.

Was this page helpful?
0 / 5 - 0 ratings