gpt4 book ai didi

javascript - 使用 Jest 模拟简单的内部函数以在渲染的 React 组件中使用

转载 作者:行者123 更新时间:2023-11-30 19:13:46 25 4
gpt4 key购买 nike

我有一个简单的 React 应用程序,包含以下 App.jsApp.test.jsutils.js 文件:

App.js

import React from 'react';
import { randomNameGenerator } from './utils.js';
import './App.css';

function App() {
return (
<div>
{randomNameGenerator()}
</div>
);
}

export default App;

App.test.js

import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect'
import App from './App';

it('allows Jest method mocking', () => {
const { getByText } = render(<App />);
expect(getByText("Craig")).toBeInTheDocument()
});

utils.js

export function randomNameGenerator() {
return Math.floor((Math.random() * 2) + 1) == 1 ? 'Steve' : 'Bill';
}

这是一个简单的例子,但我试图完成的是 randomNameGenerator() 函数的 Jest 模拟,它只返回 “Craig” 用于特定的 Jest 测试

我遵循了各种各样的教程/指南,但找不到任何有用的东西 - 我得到的最接近(“感觉”)的是这个(在 App.test.js),这没有效果:

jest.doMock('./utils', () => {
const originalUtils = jest.requireActual('./utils');
return {
__esModule: true,
...originalUtils,
randomNameGenerator: jest.fn(() => {
console.log('## Returning mocked typing duration!');
return 'Craig';
}),
};
})

它失败的方式是预期的:

Unable to find an element with the text: Craig. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

<body>
<div>
<div>
Steve
</div>
</div>
</body>

6 | it('allows Jest method mocking', () => {
7 | const { getByText } = render(<App />);
> 8 | expect(getByText("Craig")).toBeInTheDocument()
| ^
9 | });

最佳答案

您可以通过调用 jest.mock 来模拟模块,然后导入它,然后在您的测试中调用 mockImplementation 来设置正确的返回值。

import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect'
import App from './App';

import { randomNameGenerator } from "./utils";

jest.mock('./utils.js', () => ({
randomNameGenerator: jest.fn()
}));

describe('test', () => {
it('allows Jest method mocking 1', () => {
randomNameGenerator.mockImplementation(() => "Craig");
const { getByText } = render(<App />);
expect(getByText("Craig")).toBeInTheDocument()
});

it('allows Jest method mocking 2', () => {
randomNameGenerator.mockImplementation(() => "Not Craig");
const { getByText } = render(<App />);
expect(getByText("Not Craig")).toBeInTheDocument()
});
});

关于javascript - 使用 Jest 模拟简单的内部函数以在渲染的 React 组件中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com