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

Rya*_*ner 7 unit-testing mocking reactjs jestjs

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.',
            });
        );
    });
);
Run Code Online (Sandbox Code Playgroud)

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

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

如果我有一个如此定义的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>
        )   
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

export function apiGetMethod() {
   return fetch(url, {...});
}
Run Code Online (Sandbox Code Playgroud)

And*_*rle 12

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

import { apiGetMethod } from './api'

jest.mock('./api', () => ({ apiGetMethod: jest.fn() }))
Run Code Online (Sandbox Code Playgroud)

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

apiGetMethod.mockImplementation(() => Promise.resolve('test1234'))
Run Code Online (Sandbox Code Playgroud)


Val*_*tin 7

这是为 21 年遇到此问题的任何人提供的更新解决方案。此解决方案使用Typescript,因此请注意这一点。对于常规 JS,只要删除你看到的类型调用即可。

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

import functionToMock from '../api'

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

[imports are up here]

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

[tests are down here]
Run Code Online (Sandbox Code Playgroud)

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

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

现在问题来了,每个人似乎都陷入了困境。到目前为止,这是正确的,但在组件内模拟函数时,我们遗漏了一个重要的部分: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');
  });
});

Run Code Online (Sandbox Code Playgroud)


Nah*_*nde 6

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

const api = require('./api');
api.apiGetMethod = jest.fn(/* Add custom implementation here.*/);
Run Code Online (Sandbox Code Playgroud)

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