模拟与axios-mock-adapter的get请求,返回测试中未定义的响应

时间:2019-07-17 17:00:06

标签: typescript unit-testing axios axios-mock-adapter

我是新打字稿,是前端和前端。我有一个可以吸引用户的简单服务

export class MyService {
    registerUrl = 'someurl'

    getUser() {
        let user
        axios
            .get(this.registerUrl)
            .then(response => {
                user = response
                if (user === undefined) {
                    console.log('undefined')
                } else {
                    console.log('defined')
                }
                console.log('response from this service', user)
                return user
            })
            .catch(error => {
                console.log('Error fetching user', error)
            })
    }
}

我正在尝试使用getUser()模拟axios-mock-adapter请求来测试get

describe('My Service Test', () => {

  it('tests call to a service', async () => {
    const data = {..}
    const registerUrl = 'someurl'
    const mock = new MockAdapter(axios)
    mock.onGet(registerUrl).reply(200, data)
    axios.get(registerUrl)
    const resp = new MyService().getUser()
    console.log('response in test', resp)
})
})

但是测试无法正常进行。在运行时,将首先打印测试中的console.log语句,而respundefined,然后运行getUser()函数,并返回user值被填充。为什么测试中的响应undefined?我浏览了this answer,但没有使用axios.create

0 个答案:

没有答案