【问题标题】:Unit testing HTTP request with Vue, Axios, and Mocha使用 Vue、Axios 和 Mocha 对 HTTP 请求进行单元测试
【发布时间】:2017-06-05 23:48:03
【问题描述】:

我真的很难尝试使用 Mocha/Chai-Sinon 在 VueJS 中测试请求,使用 Axios 作为请求库,并尝试了 Moxios 和 axios-mock-adaptor 的混合。下面的例子是后者。

我要做的是在创建组件时发出请求,这很简单。

但测试要么抱怨 results 变量未定义,要么抱怨 async timout

我通过为getData() function? Or should Ireturn 的变量分配值来做对了吗?任何帮助将不胜感激。

组件

  // Third-party imports
  import axios from 'axios'
  // Component imports
  import VideoCard from './components/VideoCard'

  export default {
    name: 'app',
    components: {
      VideoCard
    },
    data () {
      return {
        API: '/static/data.json',
        results: null
      }
    },
    created () {
      this.getData()
    },
    methods: {
      getData: function () {
        // I've even tried return instead of assigning to a variable
        this.results = axios.get(this.API)
          .then(function (response) {
            console.log('then()')
            return response.data.data
          })
          .catch(function (error) {
            console.log(error)
            return error
          })
      }
    }
  }

测试

import Vue from 'vue'
import App from 'src/App'

import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'

let mock = new MockAdapter(axios)

describe('try and load some data from somewhere', () => {
  it('should update the results variable with results', (done) => {
    console.log('test top')
    mock.onGet('/static/data.json').reply(200, {
      data: {
        data: [
          { id: 1, name: 'Mexican keyboard cat' },
          { id: 2, name: 'Will it blend?' }
        ]
      }
    })

    const VM = new Vue(App).$mount

    setTimeout(() => {
      expect(VM.results).to.be.null
      done()
    }, 1000)
  })
})

【问题讨论】:

    标签: vue.js axios karma-mocha


    【解决方案1】:

    我不确定 moxios 模拟适配器,但我也遇到过类似的问题。我最终将 axios 和 moxios 与 vue-webpack 模板一起使用。我的目标是伪造检索一些博客文章,并断言它们被分配给 this.posts 变量。

    您的 getData() 方法应该像您说的那样返回 axios 承诺 - 这样,我们就有办法告诉测试方法承诺完成了。否则它将继续运行。

    然后在 getData() 的成功回调中,您可以分配您的数据。所以它看起来像

    return axios.get('url').then((response) {
       this.results = response
    })
    

    现在在你的测试中

    it('returns the api call', (done) => {
        const vm = Vue.extend(VideoCard)
        const videoCard = new vm()
    
        videoCard.getData().then(() => {
            // expect, assert, whatever
        }).then(done, done)
    )}
    

    注意 done() 的使用。这只是一个指南,您必须根据您正在做什么来修改它。如果您需要更多详细信息,请告诉我。我推荐使用 moxios 来模拟 axios 调用。

    这是一篇关于测试对我有帮助的 api 调用的好文章。

    https://wietse.loves.engineering/testing-promises-with-mocha-90df8b7d2e35#.yzcfju3qv

    【讨论】:

    • 感谢您的回复!你肯定在大方向上帮助了我;我已经在下面发布了我的答案。再次感谢!
    • 很高兴你得到它!干得好,存根请求绝对是要走的路。发布您的答案也很棒,这将帮助其他人。如果您对答案感到满意,可以将答案标记为已接受(:
    • 奇怪,axios-mock-adapter 对我也不起作用,承诺似乎没有兑现。 Moxios 确实有效!
    【解决方案2】:

    非常感谢xenetics post above,他帮助我指出了正确的方向。

    简而言之,我试图错误地访问数据,而我应该是using the $data property

    我也放弃了axios-mock-adaptor 并重新使用moxios

    我确实必须 return 我的组件中的承诺,就像这样;

    getData: function () {
      let self = this
      return axios.get(this.API)
        .then(function (response) {
          self.results = response.data.data
        })
        .catch(function (error) {
          self.results = error
        })
    }
    

    (使用let self = this 绕过了 axios 范围的“问题”)

    然后为了测试这一点,我所要做的就是存根请求(在分别为 beforeEach()afterEach() 执行 moxios.install()moxios.uninstall 之后。

    it('should make the request and update the results variable', (done) => {
      moxios.stubRequest('./static/data.json', {
        status: 200,
        responseText: {
          data: [
            { id: 1, name: 'Mexican keyboard cat' },
            { id: 2, name: 'Will it blend?' }
          ]
        }
      })
    
      const VM = new Vue(App)
      expect(VM.$data.results).to.be.null
    
      VM.getData().then(() => {
        expect(VM.$data.results).to.be.an('array')
        expect(VM.$data.results).to.have.length(2)
      }).then(done, done)
    })
    

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 1970-01-01
      • 2018-03-13
      • 2015-05-16
      • 2021-11-26
      • 2023-03-20
      • 2014-08-20
      • 2020-03-06
      • 2012-07-16
      相关资源
      最近更新 更多