【问题标题】:State not changing when unit testing VueJS and VueResource单元测试 Vue JS 和 Vue 资源时状态不变
【发布时间】:2016-12-21 07:03:18
【问题描述】:

我正在尝试测试我创建的使用 vue-resource 进行 API 调用的服务。该服务应该进行调用并使用新数据更新组件,但是在我的测试中它没有注册更新的值。我使用与vue-cli webpack 示例相同的设置,并且我的身份验证服务基于this repo(不幸的是没有任何测试)

我的服务:

export default {
   login(context, creds){
      context.$http.post(LOGIN_URL, creds)
        .then((response) => {
           //do something else here
        }, (response) => {
           context.error = response.data.error
        }
   }
}

我的测试:

import Vue from 'vue'
import VueResource from 'vue-resource'
Vue.use(VueResource)
import Auth from 'src/auth'

describe('Auth', () => {
   it('should throw an error on unsuccessful login', (done) => {

     //intercept the api call and force an invalid response
     Vue.http.interceptors.unshift((request, next) => {
        next(request.respondWidth({error: 'some error'}, {status: 401}));
     });


     const vm = new Vue({
        data: {
           error: ''
        }
     }).$mount()

     Auth.login(vm, {email: 'test@test.com', pass: 'test'} )

     //this always fails
     expect(vm.error).to.equal('some error')

     //ive also tried:
     vm.$nextTick(() => {
        expect(vm.error).to.equal('some error')
        //done()
     });

     //undo our interceptor
     Vue.http.interceptors.shift()

   }
}

当我运行测试时它失败了,因为它期望 '' 等于 '一些错误'。

我的怀疑是 vue-resource 使用了 Promise。

【问题讨论】:

    标签: unit-testing karma-runner vue.js vue-resource


    【解决方案1】:

    在阅读了一些 Vue.js 测试后,我找到了答案。我没有使用 vm.$nextTick,而是执行了以下操作:

    setTimeout(function(){
       expect(vm.error).to.equal('something')
       done()
    }, 0)
    

    【讨论】:

    • 没有陷入 vue 错综复杂的深渊,我相信这是因为当您设置超时时,它会在其余代码之后运行,因为它位于调用堆栈的底部。因此,当它运行时,其他所有内容都已更新。那里有一些关于调用堆栈的很好的解释,应该可以澄清一下。
    猜你喜欢
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2020-08-04
    • 2023-01-03
    • 2019-01-02
    • 2021-09-15
    • 2019-04-18
    相关资源
    最近更新 更多