Javascript Vue单元测试:使用错误导入组件的函数
我正在尝试将单元测试改造为我们开发的旧Vue应用程序。我的上级设置的一个问题是,我不能更改实际应用程序中的任何代码(这对我来说太麻烦了) 现在,我尝试测试当用户单击按钮时是否激活了一个方法:Javascript Vue单元测试:使用错误导入组件的函数,javascript,unit-testing,vue.js,sinon,chai,Javascript,Unit Testing,Vue.js,Sinon,Chai,我正在尝试将单元测试改造为我们开发的旧Vue应用程序。我的上级设置的一个问题是,我不能更改实际应用程序中的任何代码(这对我来说太麻烦了) 现在,我尝试测试当用户单击按钮时是否激活了一个方法: import { mount, shallowMount, createLocalVue } from '@vue/test-utils'; import { expect } from 'chai'; import Vuex from 'vuex'; import sinon from 'sinon';
import { mount, shallowMount, createLocalVue } from '@vue/test-utils';
import { expect } from 'chai';
import Vuex from 'vuex';
import sinon from 'sinon';
import AccountCreation from '@/components/.../AccountCreation.vue';
import createStoreConfig from '@/store/create-store-config';
const localVue = createLocalVue();
localVue.use(Vuex);
const storeConfig = createStoreConfig();
const store = new Vuex.Store(storeConfig);
store.state.selectedMemberType = 'writer';
describe('Account Creation', () => {
const wrapper = shallowMount(AccountCreation, {
methods: {
},
store,
localVue,
});
it('should return a writer argument when the validate username button is clicked', () => {
let ga = () => {console.log('test')}
const button = wrapper.find('#accountCreation .col-xl-5 .card span ').trigger('click')
})
});
我知道在这个测试中没有expect
。
实际的方法是这样的。我知道该方法正在被触发,但mocha
/chai
在设置成功之前抛出错误
我不能分享实际的代码,但基本上它会这样做:
validateUsername(fieldName) {
ga('send', 'event', 'page' 'action' 'error')
}
代码还有更多内容,但没有一个是经过运行的,因为
ga
在运行时会抛出ReferenceError
。Google Analytics是在main.js
中奇怪地导入的,所以我不能用正常的sinon
或mocha
方式存根它。你可以通过全局
对象(即setglobal.ga
)模拟ga
:
注意,此global.ga
修改对于文件中的每个测试都是持久的,而不是跨文件的
it('should return a writer argument when the validate username button is clicked', () => {
global.ga = () => {console.log('test')}
const button = wrapper.find('#accountCreation .col-xl-5 .card span ').trigger('click')
})