【发布时间】: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