我是新打字稿,是前端和前端。我有一个可以吸引用户的简单服务
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
语句,而resp
是undefined
,然后运行getUser()
函数,并返回user
值被填充。为什么测试中的响应undefined
?我浏览了this answer,但没有使用axios.create