Vue无法等待axios Post请求完成的问题

3

我在测试登录请求,但jest没有调用模拟函数:

这是我的测试:

const User = '123123'

jest.mock('axios', () => ({
  get: jest.fn(),
  post: (_url, _body) => new Promise((resolve, reject) => {
    if (_body.username != User) return reject({ data: { auth: false } })
    resolve({
      data: {
        auth: true,
        data: '123456789789213',
        name: 'Indra'
      }
    })
  })
}))

describe('Component', () => {
  let actions
  let store

  beforeEach(() => {
    actions = {
      logIn: jest.fn()
    }
    store = new Vuex.Store({
      actions
    })
  })
test('Logins in server', () => {
    const wrapper = shallowMount(Login, { store, localVue })

    const inputLogin = wrapper.find('[name=login]')
    const inputPassword = wrapper.find('[name=password]')

    //fake user and password
    inputLogin.element.value = User
    inputPassword.element.value = 'Indra1234'

    wrapper.find('button').trigger('click')
    expect(actions.logIn).toHaveBeenCalled()
  })
})

这是我的登录功能

methods : {
        AuthUser () {
            if(this.server == "Selecione um servidor") return this.$swal('Atenção', 'Favor selecionar um servidor!', 'error');
            console.log("Solicitando login")
            this.loading = true
            try {
                axios.post(this.server+"/auth",
                {
                    username: this.id,
                    password: this.password
                })
                .then(result => {
                    console.log(result)
                    if(result.data.auth) {
                        this.tk = result.data.data
                        this.nome = result.data.name
                        this.logIn
                        setTimeout(() => {
                            console.log("oi")
                            $("body, this").css("background-color","#FBF5F3");
                            // this.$router.push('/home')
                            this.$eventHub.$emit('logIn', 1);
                        }, 1000);

                    } else {
                        this.loading = false
                        this.$swal('Atenção', 'Usuário ou senha incorretos!', 'warning');
                    }
                }).catch((er) => {
                    this.loading = false
                    this.$swal('Desculpe', 'Ocorreu um erro de comunicação com o servidor!', 'error');
                    console.log(er)
                })
            } catch (error) {
                this.loading = false
                this.$swal('Desculpe', 'Ocorreu um erro ao realizar o login', 'error');
                console.log('Erro interno: ', error)
            }

        }
    }

当我运行测试时

enter image description here

请注意,控制台日志"Solicitando login(请求登录)"已被调用。 该测试的配置由Vue cli 3完成,我正在使用https://lmiller1990.github.io/vue-testing-handbook/vuex-actions.html#creating-the-action作为参考。

2个回答

1
我看不到你在清空承诺。你可以尝试使用flush promise库吗?
npm i --save-dev flush-promises

然后...

// up top
import flushPromises from 'flush-promises';

//...
    wrapper.find('button').trigger('click');
    await flushPromises();
    expect(actions.logIn).toHaveBeenCalled();

更多信息请查看这里... https://vue-test-utils.vuejs.org/guides/testing-async-components.html


0
问题出在我设置输入值的时候。
当我使用 console.log(wrapper.vm.id, wrapper.vm.password) 输出日志时,它们是 null。
为了解决这个问题,
    inputLogin.element.value = User
    inputLogin.trigger('input');
    inputPassword.element.value = 'Indra1234'
    inputPassword.trigger('input');

当然还有 flushPromises()。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接