Jest -- 模拟在 React 组件内部调用的函数

27

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()实现,以便我可以测试它是否正确地渲染数据。

(这只是为了理解如何模拟在React组件内调用的函数而简化的例子)

编辑:为了清楚起见,附上api.js文件

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

export function apiGetMethod() {
   return fetch(url, {...});
}

1
apiGetMethod 是如何注入到你的模块中的? - Andreas Köberle
Foo 组件文件的顶部,加入以下代码:import { apiGetMethod } from './api'; - Ryan Castner
4个回答

32

你需要模拟 ./api 模块,并像这样导入它,以便你可以设置模拟的实现方式。

import { apiGetMethod } from './api'

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

您可以使用mockImplementation来设置模拟的工作方式:

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

我按照将模拟数据放在__mocks__/api.js中并调用jest.mock('./api')的方式来创建模拟数据,但它没有引入模拟数据。我是按照https://facebook.github.io/jest/docs/tutorial-async.html#content的步骤进行操作的。 - Ryan Castner
这行代码在哪个文件中:jest.mock('./api', () => ({ apiGetMethod: jest.fn() }))?是在测试文件中吗? - YPCrumble
@YPCrumble 是的,在测试文件中。 - Andreas Köberle
如果在上面的例子中,您想要模拟或监视makeRequest怎么办?我正在编写一个类似的测试,只想测试makeRequest被触发的频率。这可能吗?(在这种情况下,我不关心makeRequest中的内容。) - hairbo

8

如果@Andreas的答案中的jest.mock方法无法使用,请在测试文件中尝试以下内容。

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

这将执行您在Foo组件中模拟的apiGetMethod版本。


1
这实际上是我最终所做的,模拟内部实现:jest.fn(() => { return ... }) - Ryan Castner
你能在这里展示最终的代码吗?我也遇到了同样的问题,谢谢 @RyanCastner - Roy

6

以下是关于此问题的更新解决方案,适用于在'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。你可以在此处 了解更多信息,但基本上我们想要在渲染时将其包装在此 act 中。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');
  });
});


-1
另一种模拟这个的解决方案是:
window['getData'] = jest.fn();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接