0

我有一个 laravel 项目。我正在尝试测试一个 vue 组件,但它显示错误:这是我的测试:test.spec.js

import { mount } from '@vue/test-utils';
import expect from 'expect';
import moxios from 'moxios';
import Post from '../../resources/js/components/Component.vue';

describe('Component',()=>{

    let wrapper;

   beforeEach(() => {

        moxios.install();  

        wrapper = mount(Component, {
            propsData: {
                data: {
                    id: 1,
                    name: 'Test'
                    lastname: 'Test
                }
            }
        });

   });

   afterEach(() => {
     moxios.uninstall();
   });

   it.only('updates the profile user after being liked', (done) => {  

      click('button.like');

      moxios.wait(() => {
            let request = moxios.requests.mostRecent()
            request.respondWith({
              status: 200              
            }).then(function () {
              seeText('1 likes')
              done()
            })
        });

   });

   let click = selector => {
        wrapper.find(selector).trigger('click');
   };    

});

这是组件:Component.vue

<template>
    <div class="profile">                                                             

       <div>
        {{ name }}
       </div>
              <div>
        {{ lastname}}
       </div> 

       <button class="like" @click="like">Like</button>


    </div>  
</template>

<script>
export default {

  props:['data'],       

        data(){
            return {
                id:this.data.id,
                name: this.data.name,
                lastname :this.data.lastname
                .......

            };
        },

        methods:{

          like(){
                axios.post(`/user/${this.id}/likes`);
                ......

            }

        }

}
</script>

并且在测试的时候显示:axios没有定义,但是在resources/js/bootstrap.js中全局定义了

window.axios = require('axios');

它适用于浏览器!

然后我在 Component.vue 中添加了这个

<script>
import axios from 'axios';
.....
</script>

现在我的测试工作正常。但如果删除它,它会再次失败。我只是想知道为什么会发生这种情况,我不确定是否必须添加import axios from 'axios';对每个使用 axios 进行测试的组件

4

1 回答 1

1

在你的 setup.js 中添加这样的 axios:

require('jsdom-global')();

global.axios = require('axios');
于 2020-04-21T13:16:25.530 回答