加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:46:11 所属栏目:百科 来源:网络整理
导读:Jest提供了一种模拟函数的方法,如文档中所述 apiGetMethod = jest.fn().mockImplementation( new Promise((resolve,reject) = { const userID = parseInt(url.substr('/users/'.length),10); process.nextTick( () = users[userID] ? resolve(users[userID])
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'))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读