[Vuejs]-Vuejs Test Utils with Jest – stuck testing async service

0πŸ‘

I am still having the problem described above but I did figure out that if you change the style of handling promises from async/ await to a standard <promise>.then() I was able to get the tests to pass.

here’s an example component with an example test:

  <ul>
    <li 
      v-for="notification in notifications" 
      :key="notification.id"
    >
      {{notification.body}}
    </li>
  </ul>
</template>
<script>
import axios from 'axios';

export default {
  data(){
    return {
      notifications: []
    }
  },
  methods:{
    getNotifications(){
      axios.get('/notifications.json')
        .then(response =>  this.notifications = response.data.data)
    }
  },
  mounted(){
    this.getNotifications();
  }
}
</script>
import AppNotifications from '../AppNotifications';

jest.mock('axios', () => {
  return {
    get: () => Promise.resolve({
      data: {
        "data": [{
            "id": 1,
            "body": "first notification",
            "read": "true"
          },
          {
            "id": 2,
            "body": "second notification",
            "read": "false"
          }
        ]
      }
    })
  }
})

describe('AppNotification', () => {
  it('renders a list of notifications', async() => {
    let wrapper = mount(AppNotifications)
    await wrapper.vm.$nextTick(() => {    
      let items = wrapper.findAll('li');
      expect(items.at(0).text()).toContain('first notification')
      expect(items.at(1).text()).toContain('second notification')
    });
  });
})```

Leave a comment