gpt4 book ai didi

vue.js - 使用 Vue、Axios 和 Mocha 对 HTTP 请求进行单元测试

转载 作者:搜寻专家 更新时间:2023-10-30 22:10:43 24 4
gpt4 key购买 nike

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

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

但测试要么提示 results 变量未定义,要么提示 异步超时

我通过分配 getData() 函数的变量是否正确?或者我应该返回值?任何帮助将不胜感激。

组件

  // 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)
})
})

最佳答案

我不确定 moxios 模拟适配器,但我有过类似的挣扎。我最终使用了带有 vue-webpack 模板的 axios 和 moxios。我的目标是伪造检索一些博客文章,并断言它们已分配给 this.posts 变量。

您的 getData() 方法应该像您所说的那样返回 axios promise - 这样,我们就有办法告诉测试方法 promise 已完成。否则它只会继续前进。

然后在 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

关于vue.js - 使用 Vue、Axios 和 Mocha 对 HTTP 请求进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41772956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com