如何模拟AuthService组件的功能?

我正在使用Jest /酶来测试反应成分,并遇到这些错误。我尝试尝试模拟此AuthService.fetch函数的代码有很多排列。如何正确模拟回应?

it('state update',() => {
    const props = {
        comment: {
            id: 97,text: "yo",created: "2019-11-03T13:40:34.496180-05:00",likes: 0,dislikes: 0
        }

    }

    const component = mount(<Comment {...props}/>);
    //const component = shallow(<Comment {...props}/>);
    component.checkUserLikedComment = jest.fn();
    jest.mock('../components/home/AuthService',() => ({
        fetch: () => Promise.resolve('someEmail') //=>jest.fn()
    }));
    // fetch.mockImplementation(() => Promise.resolve('someEmail'));
    // fetch.mockImplementation(() => 'someEmail');
    // AuthService.fetch.mockImplementation(()=> Promise.resolve('someEmail'));

    // expect(component.find('.email').text()).toEqual('');
    component.update();
    expect(component.find('.email').text()).toEqual('someEmail');

这是Comment.js

function Comment(props) {

const Auth = new AuthService();
const [email,setEmail] = useState('');
const [likeStatus,setLikeStatus] = useState(0);
const [comment,setComment] = useState(props.comment);
const text = props.comment.text;
const id = props.comment.id;
const likes = comment.likes;
const dislikes = comment.dislikes;
const numLikes = likes - dislikes;

useEffect(() => {
    const options = {
        method: 'POST',body: JSON.stringify({
            "comment_id": id,})
    }


    Auth.fetch('/api/comments/get_user_email_for_comment/',options).then((data) => {
        console.log(data)
        setEmail(data);
    })
        .catch((rej) => {
        console.log(rej)
    });

    checkUserLikedComment();

},[likeButtonStyle,dislikeButtonStyle])

以下是错误消息:

(node:61816) UnhandledPromiseRejectionWarning: FetchError: invalid JSON response body at undefined reason: Unexpected end of JSON input

(节点:61816)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。该错误是由于在没有catch块的情况下抛出异步函数而产生的,或者是由于拒绝了未使用.catch()处理的Promise而产生的。 (拒绝ID:3) (节点:61816)[DEP0018] DeprecationWarning:已弃用未处理的承诺拒绝。将来,未处理的承诺拒绝将以非零退出代码终止Node.js进程。  失败项目/前端/src/jest/Comment.spec.js   ●控制台

console.log project/frontend/src/components/comment/Comment.js:33
  FetchError {
    message:
     'invalid json response body at undefined reason: Unexpected end of JSON input',type: 'invalid-json' }

›状态更新

expect(received).toEqual(expected) // deep equality

Expected: "email"
Received: ""
xue5227980 回答:如何模拟AuthService组件的功能?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3162329.html

大家都在问