【问题标题】:Why is axios ignoring the .then? [duplicate]为什么 axios 忽略 .then? [复制]
【发布时间】:2021-08-21 23:14:47
【问题描述】:

我有以下单元测试进行休息调用,但我的 axios.get 之后的所有内容都没有运行。

restCalls.spec.js:

import {getData} from '@/jgapi.js'
describe('Axios testing', () =>
{    
it('Make an rest call from a unit test', async() => {

    var login = false
    var usr = 'bossman'
    var pass = 'bigboss!!'
    
    getData(usr, pass, (res) => {
        console.log("BEFORE IF")
        if (res.data.CurMember.name == 'bossman')
        {
            console.log("IF TRUE")
            login =  true
        }
        else 
        {
            console.log("IF FALSE")
            login = false
        }
    }, 
    (err) => {
        console.log("ERROR ERROR" + err)
    })

    expect(login == true)
})    
})

这是使用 axios 进行其余调用的文件

jgapi.js:

import axios from 'axios'

export function getData(user, pass, callBack, errorCallBack)
{
    console.log("BEFORE axios " + user + " " + pass)
    axios.get('http://localhost:8080/properties', 
    {
        auth: 
        {
            username: user, 
            password: pass
        }
    })
    //everything here down isn't running
    .then(res => {
        console.log("Inside axios then" )
        callback(res)
    })
    .catch(err => {
        if(errorCallBack != null){
            console.log("Inside asios error")
            errorCallBack(err);
        }
    })
}

在我的单元测试中,我通过了,但是 axios 的 .then 部分甚至没有被调用,我也从未在单元测试中取回我的数据进行验证。任何帮助将不胜感激!

控制台:

PASS  tests/unit/restCalls.spec.js
  Axios testing
    ✓ Make an rest call from a unit test (26ms)

  console.log src/jgapi.js:6
    BEFORE axios bossman bigboss!!

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.628s

【问题讨论】:

  • 在您的测试用例中在getData 之前添加await。并使您的 getData 函数返回 axios.get
  • 嘿,这很好,您可以将其作为答案提交,我会将其标记为正确

标签: javascript rest unit-testing axios


【解决方案1】:

问题是您的getData 函数返回未定义。虽然在“后台”中启动 axios 请求。您的测试用例调用它并立即进入下一行 (expect(login == true))。

要修复它,您应该让getData 函数返回由axios.get 承诺创建的。并在测试用例中的getData 调用之前添加await 以等待它完成。

【讨论】:

    猜你喜欢
    • 2023-02-22
    • 2015-11-08
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 2020-06-16
    相关资源
    最近更新 更多