【问题标题】:Jest -- Mock a function called inside a React Component玩笑——模拟在 React 组件中调用的函数
【发布时间】:2017-04-19 15:37:00
【问题描述】:

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, {...});
}

【问题讨论】:

  • apiGetMethod 是如何注入到你的模块中的?
  • import { apiGetMethod } from './api';Foo 组件文件的顶部

标签: unit-testing reactjs mocking jestjs


【解决方案1】:

您必须像这样模拟 ./api 模块并导入它,以便您可以设置模拟的实现

import { apiGetMethod } from './api'

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

在您的测试中可以使用mockImplementation 设置模拟的工作方式:

apiGetMethod.mockImplementation(() => Promise.resolve('test1234'))

【讨论】:

  • 我通过将其放入 __mocks__/api.js 然后调用 jest.mock('./api') 来跟踪模拟的创建,但它没有拉模拟,我在关注 facebook.github.io/jest/docs/tutorial-async.html#content
  • 这一行在哪个文件中:jest.mock('./api', () =&gt; ({ apiGetMethod: jest.fn() }))?在测试中?
  • @YPCrumble 是在测试文件中
【解决方案2】:

如果@Andreas 的答案中的jest.mock 方法对您不起作用。您可以在测试文件中尝试以下操作。

const api = require('./api');
api.apiGetMethod = jest.fn(/* Add custom implementation here.*/);

这应该在Foo 组件内部执行apiGetMethod 的模拟版本。

【讨论】:

  • 这实际上是我最终做的,嘲笑里面的实现:jest.fn(() =&gt; { return ... })
  • 你能在这里显示fanilly代码吗,我也有同样的问题,谢谢@RyanCastner
【解决方案3】:

这是一个更新的解决方案,适用于 21 年遇到此问题的任何人。此解决方案使用 Typescript,因此请注意这一点。对于普通的 JS,只要在你看到它们的地方取出类型调用。

您在顶部的测试中导入函数

import functionToMock from '../api'

然后您确实在测试之外模拟了对 文件夹 的调用,以表明从此文件夹中调用的任何内容都应该并且将被模拟

[imports are up here]

jest.mock('../api');

[tests are down here]

接下来我们模拟我们要导入的实际函数。就我个人而言,我在测试中这样做了,但我认为它在测试之外或在 beforeEach 内也同样有效

(functionToMock as jest.Mock).mockResolvedValue(data_that_is_returned);

现在这是踢球者,每个人似乎都被卡住了。到目前为止,这是正确的,但我们在组件内模拟函数时遗漏了一个重要的部分:act。你可以阅读更多关于它的信息here,但本质上我们想将我们的渲染包装在这个动作中。 React 测试库有自己的act 版本。它也是异步的,因此您必须确保您的测试是异步的,并且还要在其外部定义来自 render 的解构变量。

最后你的测试文件应该是这样的:

import { render, act } from '@testing-library/react';
import UserGrid from '../components/Users/UserGrid';
import { data2 } from '../__fixtures__/data';
import functionToMock from '../api';

jest.mock('../api');

describe("Test Suite", () => {
  it('Renders', async () => {
    (functionToMock as jest.Mock).mockResolvedValue(data2);

    let getAllByTestId: any;
    let getByTestId: any;
    await act(async () => {
      ({ getByTestId, getAllByTestId } = render(<UserGrid />));
    });
    const container = getByTestId('grid-container');
    const userBoxes = getAllByTestId('user-box');
  });
});

【讨论】:

  • 你拯救了我的一天。
【解决方案4】:

模拟这个的另一个解决方案是:

window['getData'] = jest.fn();

【讨论】:

    猜你喜欢
    • 2021-10-14
    • 2020-01-31
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2022-07-08
    • 2019-10-01
    • 2019-04-11
    • 2017-07-27
    相关资源
    最近更新 更多