0

I have a laravel project. I am trying to test a vue component and it was showing errors: This is my test: 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');
   };    

});

This is the component: 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>

And when testing it shows: axios is not defined, but it is defined globally in resources/js/bootstrap.js

window.axios = require('axios');

and it works on the browser!

Then I added this in Component.vue

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

And now my tests works fine. but if a remove it, it fails again. I just wanted to know why this happens, I am not sure if I have to add import axios from 'axios'; to every component that uses axios just for testing

Luis
  • 325
  • 4
  • 20

1 Answers1

1

In your setup.js add axios like this:

require('jsdom-global')();

global.axios = require('axios');
ax2to
  • 11
  • 3