如何解决我正在用与身份验证有关的React编写一个测试用例使用axios,但是由于测试用例没有通过而被卡住了
现有代码: loginUser.js:
import { getUserDetails } from '../api/userDetails';
import { mapApiObjectToModel } from '../mapper/userProfileMapper';
import axios from 'axios';
export const getLoggedInUserDetails = async () => {
axios
.get('/api/getUserDetails')
.then(response => {
return mapApiObjectToModel(response);
})
.catch(err => {
console.log('error==',err);
});
};
userProfileMapper.js:
export const mapApiObjectToModel = inputObj => {
const outputObj = {};
const authorizedRoles = ['Admin'];
if (inputObj) {
outputObj.fullName = '';
if (inputObj.data) {
outputObj.fullName = inputObj.data.data;
}
outputObj.role = 'Admin';
outputObj.isAuthorized = authorizedRoles.includes(outputObj.role);
}
console.log('outputObj',outputObj);
return outputObj;
};
loginUser.test.js:
import axios from 'axios';
import getLoggedInUserDetails from '../../action/loginUser';
jest.mock('axios');
describe('routes using memory router',() => {
it('Get Admin message',async () => {
const data = 'Admin';
axios.get.mockImplementationOnce(() => Promise.resolve(data));
console.log(data);
await expect(getLoggedInUserDetails()).resolves.toEqual(data);
expect(axios.get).toHaveBeenCalledWith('/api/getUserDetails');
});
it('fetches erroneously data from an API',async () => {
const errorMessage = 'Network Error';
axios.get.mockImplementationOnce(() => Promise.reject(new Error(errorMessage)));
await expect(getLoggedInUserDetails()).rejects.toThrow(errorMessage);
});
});
我真的是所有这些人的新手,所以将不胜感激。甚至在TDD上针对userProfileMapper.js的任何建议都将不胜感激:)
解决方法
mapApiObjectToModel
返回的对象类似,
{
role: 'ADMIN',isAuthorized: true
}
但是,在测试中,您希望它等于字符串“ Admin”
const data = 'Admin';
...
await expect(getLoggedInUserDetails()).resolves.toEqual(data); // Note that you have initialize data to 'Admin'
尝试将数据更改为对象,例如
const data = {
role: 'Admin',isAuthorized: true
};
...
await expect(getLoggedInUserDetails()).resolves.toEqual(data);
,
已更新: loginUser.js :
import { getUserDetails } from '../api/userDetails';
import { mapApiObjectToModel } from '../mapper/userProfileMapper';
import axios from 'axios';
export const getLoggedInUserDetails = () => {
return axios
.get('/api/getUserDetails')
.then(response => {
return mapApiObjectToModel(response);
})
.catch(err => {
console.log('error==',err);
throw err;
});
};
您的功能getLoggedInUserDetails
出现以下问题,
- 您没有从函数中返回承诺。
- 在访问测试文件 loginUser.test.js:中的
async
时,您不需要expect(Promise).resolves
。 - 如果要测试对承诺的拒绝或删除catch块,则需要将
err
从catch块中抛出。
我已将以下项目更新为功能getLoggedInUserDetails
,
- 从
async
中删除了export const getLoggedInUserDetails = async () => {
- 从
axios.get('/api/getUserDetails')
退回了诺言 - 添加了
throw err
来阻止拦截
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。