单元测试 – Jest – 模拟在React组件内部调用的函数

前端之家收集整理的这篇文章主要介绍了单元测试 – Jest – 模拟在React组件内部调用的函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Jest提供了一种模拟函数方法,如文档中所述
apiGetMethod = jest.fn().mockImplementation(
    new Promise((resolve,reject) => {
        const userID = parseInt(url.substr('/users/'.length),10);
        process.nextTick(
            () => users[userID] ? resolve(users[userID]) : reject({
                error: 'User with ' + userID + ' not found.',});
        );
    });
);

但是,当在测试中直接调用函数时,这些函数似乎只能工作.

describe('example test',() => {
    it('uses the mocked function',() => {
        apiGetMethod().then(...);
    });
});

如果我有一个如此定义的React组件,我该如何模拟它?

import { apiGetMethod } from './api';

class Foo extends React.Component {
    state = {
        data: []
    }

    makeRequest = () => {
       apiGetMethod().then(result => {
           this.setState({data: result});
       });
    };

    componentDidMount() {
        this.makeRequest();
    }

    render() {
        return (
           <ul>
             { this.state.data.map((data) => <li>{data}</li>) }
           </ul>
        )   
    }
}

我不知道如何制作它,所以Foo组件调用我的模拟apiGetMethod()实现,以便我可以测试它是否正确呈现数据.

(这是一个简化的,人为的例子,为了理解如何模拟内部反应组件的函数)

编辑:api.js文件为清楚起见

// api.js
import 'whatwg-fetch';

export function apiGetMethod() {
   return fetch(url,{...});
}
您必须像这样模拟./api模块并导入它,以便您可以设置模拟的实现
import { apiGetMethod } from './api'

jest.mock('./api',() => ({ apiGetMethod: jest.fn() }))

在您的测试中可以使用mockImplementation设置模拟应该如何工作:

apiGetMethod.mockImplementation(() => Promise.resolve('test1234'))
原文链接:https://www.f2er.com/react/300915.html

猜你在找的React相关文章