gpt4 book ai didi

reactjs - 我如何通过类原型(prototype)或 enzyme 包装器实例正确地监视 react 组件的方法?

转载 作者:行者123 更新时间:2023-12-05 04:00:53 25 4
gpt4 key购买 nike

当我使用 Jest 和 Enzyme 模拟点击时,我试图断言 React 类组件方法被调用。当我尝试监视类原型(prototype)或 wrapper.instance() 时,我得到 Error: Cannot spy the searchBooks property because it is not a function;改为未定义

我的相关依赖项:

"devDependencies": {
"enzyme": "^3.9.0"
"enzyme-adapter-react-16": "^1.6.0",
"jest": "^23.6.0",
"jest-enzyme": "^7.0.1",
"ts-jest": "^23.10.3",
"typescript": "^3.1.1",

...

"dependencies": {
"@material-ui/core": "^3.2.0",
"@material-ui/icons": "^3.0.1",
"@material-ui/lab": "^3.0.0-alpha.23",
"react": "^16.5.2",

我已经尝试过这些选项,它们会引发前面提到的错误。

 let spy = jest.spyOn(wrapper.instance() as MyComponentClass, 'methodName');
let spy2 = jest.spyOn(MyComponentClass.prototype, 'methodName');

我可以用下面的方法消除错误,但 spy 仍然没有被调用。

let spy3 = jest.spyOn(wrapper.find(MyComponentClass).instance() as MyComponentClass, 'methodName');

下面是我的代码。

import * as React from 'react';
import { Fragment, Component, ChangeEvent } from 'react';
import { AudioType } from '../../model/audio';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import BookSearchStyles from './BookSearchStyles';
import BookDetail from './BookDetail';
import SearchIcon from '@material-ui/icons/Search';
import IconButton from '@material-ui/core/IconButton';
import { VolumeInfo } from '../../model/volume';

export interface BookSearchProps extends WithStyles<typeof BookSearchStyles> {
search?: (query: string) => void;
}

export interface BookSearchState {
searchQuery?: string;
}

export class BookSearch extends Component<BookSearchProps, BookSearchState> {
state: BookSearchState = {
searchQuery: '',
};

handleChange = (event: ChangeEvent<HTMLInputElement>) => {
this.setState({
[event.target.name]: event.target.value,
});
};

searchBooks = () => {
if (this.state.searchQuery) {
this.props.search(this.state.searchQuery);
}
};

render() {
const { classes, volumes } = this.props;
return (
<Fragment>
<div className={classes.searchPrompt}>
<form className={classes.formContainer}>
<div className={classes.search}>
<TextField
id="query-text-field"
name="searchQuery"
label="enter book title or author"
className={classes.textField}
value={this.state.searchQuery}
onChange={this.handleChange}
fullWidth={true}
/>
{
<IconButton
onClick={this.searchBooks}
data-test="search-button"
>
<SearchIcon />
</IconButton>
}
</div>
</form>
</div>
</Fragment>
);
}
}

export default withStyles(BookSearchStyles)(BookSearch);

我的测试

import * as React from 'react';
import { mount, ReactWrapper } from 'enzyme';
import BookSearchWrapped from './index';
import { BookSearch, BookSearchProps, BookSearchState } from './index';

describe("<BookSearch />", () => {

let wrapper: ReactWrapper<BookSearchProps, BookSearchState, BookSearch>;
let component: ReactWrapper<BookSearchProps, BookSearchState>;
let search: (query: string) => void;

beforeEach(() => {
search = jest.fn();
wrapper = mount(
<BookSearchWrapped
search={search}
/>
);
component = wrapper.find(BookSearch);
});

it('renders successfully', () => {
expect(wrapper.exists()).toBe(true);
});

it("doesn't call props.search() function when the query string is empty", () => {
let spy = jest.spyOn(wrapper.instance() as BookSearch, 'searchBooks'); //THROWS ERROR
let spy2 = jest.spyOn(BookSearch.prototype, 'searchBooks'); //THROWS ERROR
let spy3 = jest.spyOn(component.instance() as BookSearch, 'searchBooks'); //NOT CALLED

wrapper.find(`IconButton[data-test="search-button"]`).simulate('click');
expect(spy).toHaveBeenCalled();
expect(spy2).toHaveBeenCalled();
expect(spy3).toHaveBeenCalled();
expect(search).not.toHaveBeenCalled();
});
});

理想情况下,我应该能够做类似 Jest spyOn function called 的事情.

最佳答案

searchBooks 是一个实例属性...

...所以在实例存在之前它不存在,您只能使用实例来监视它...

...但它也直接绑定(bind)到 onClick...

...这意味着在组件重新呈现之前,将 searchBooks 包装在 spy 中不会有任何效果。

所以修复它的两个选项是使用箭头函数调用 searchBooks,或者在测试 onClick 之前重新渲染组件,以便它绑定(bind)到 spy 的原始功能。

这是一个演示这两种方法的简单示例:

import * as React from 'react';
import { shallow } from 'enzyme';

class MyComponent extends React.Component {
func1 = () => { } // <= instance property
func2 = () => { } // <= instance property
render() { return (
<div>
<button id='one' onClick={this.func1}>directly bound</button>
<button id='two' onClick={() => { this.func2() }}>arrow function</button>
</div>
); }
}

test('click', () => {
const wrapper = shallow<MyComponent>(<MyComponent/>);
const spy1 = jest.spyOn(wrapper.instance(), 'func1');
const spy2 = jest.spyOn(wrapper.instance(), 'func2');

wrapper.find('#one').simulate('click');
expect(spy1).not.toHaveBeenCalled(); // Success! (onClick NOT bound to spy)
wrapper.find('#two').simulate('click');
expect(spy2).toHaveBeenCalledTimes(1); // Success!

wrapper.setState({}); // <= force re-render (sometimes calling wrapper.update isn't enough)

wrapper.find('#one').simulate('click');
expect(spy1).toHaveBeenCalledTimes(1); // Success! (onClick IS bound to spy)
wrapper.find('#two').simulate('click');
expect(spy2).toHaveBeenCalledTimes(2); // Success!
});

关于reactjs - 我如何通过类原型(prototype)或 enzyme 包装器实例正确地监视 react 组件的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55860188/

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