如何使用 Typescript 将 jest.spyOn 与 React 函数组件一起使用
How to use jest.spyOn with React function component using Typescript
我正在使用 Typescript 和钩子开发一个 React 应用程序,我正在尝试将 Enzyme 与 Jest 结合使用来测试功能组件。我无法使用 jest.spyOn 来测试我的组件中的方法。 jest.spyOn 方法无法正确解析并在悬停时显示以下消息
"Argument of type '"validateBeforeSave"' is not assignable to
parameter of type '"context" | "setState" | "forceUpdate" | "render" |
"componentDidMount" | "shouldComponentUpdate" | "componentWillUnmount"
| "componentDidCatch" | "getSnapshotBeforeUpdate" | ... 6 more ... |
"UNSAFE_componentWillUpdate"'.ts(2345)"
我试图将实例转换为 'Any' -
const instance = wrapper.instance() as any;
这当然忽略了编译时的问题,但随后测试抛出组件上不存在函数的运行时错误。
Cannot spy the validateBeforeSave property because it is not a
function; undefined given instead
// Some function Component
const SomeComponent = (props: IMyComponentProps) => {
const { classes } = props;
// Component has state
const [count, setCount] = useState(0);
function validateBeforeSave(){
}
function handleClick() {
validateBeforeSave();
.
.
.
}
return (
<div>
<Button>
className="saveBtn"
onClick={handleClick}
</Button>
</div>
);
};
// Unit test
describe('SomeComponent' () => {
it('validates model on button click', () => {
const wrapper = mount(
<MuiThemeProvider theme={theme}>
<SomeComponent/>
</MuiThemeProvider>,
);
const instance = wrapper.instance();
const spy = jest.spyOn(instance, "validateBeforeSave");
wrapper
.find('.saveBtn')
.at(0)
.simulate('click');
expect(spy).toHaveBeenCalledTimes(1);
});
}
我在这里错过了什么? spyOn 如何与函数组件一起工作?
我使用 create-react-app 模板创建了应用程序,它具有测试包的这些依赖项
"devDependencies": {
"ts-jest": "^23.10.3",
"@types/jest": "24.0.9",
"@types/enzyme": "^3.9.1",
"@types/enzyme-adapter-react-16": "^1.0.2",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.11.2",
"enzyme-to-json": "^3.3.5",
}
您的 validateBeforeSave
函数在 SomeComponent
中声明,使其成为无法在外部访问的 closed/private 作用域函数。您可以将该函数作为道具传递,然后您可以创建间谍并将其作为道具值传递到您的测试中,并测试传递的道具函数(间谍)是否被调用
所以你会像这样修改你的函数:
// some validator function
function validateBeforeSave(){
...
}
// Some function Component
const SomeComponent = (props: IMyComponentProps) => {
const { classes, validateBeforeSave } = props;
// Component has state
const [count, setCount] = useState(0);
function handleClick() {
validateBeforeSave();
.
.
.
}
return (
<div>
<Button>
className="saveBtn"
onClick={handleClick}
</Button>
</div>
);
};
并且在你的单元测试中,是这样的:
// Unit test
describe('SomeComponent' () => {
it('validates model on button click', () => {
const validateSpy = jest.fn();
const wrapper = mount(
<MuiThemeProvider theme={theme}>
<SomeComponent validateSpy={validateSpy}/>
</MuiThemeProvider>,
);
const instance = wrapper.instance();
wrapper
.find('.saveBtn')
.at(0)
.simulate('click');
expect(validateSpy).toHaveBeenCalledTimes(1);
});
}
我也遇到了同样的问题 - 我喜欢下面的 -
import * as React from 'react';
const SampleComponent = () => {
const sampleMethod = () => {
console.log('hello world');
};
return <button onClick={sampleMethod} type="button">Click Me</button>;
};
export default SampleComponent;
测试 -
import React from 'react';
import SampleComponent from './';
import { shallow } from 'enzyme';
describe('SampleComponent', () => {
test('should handle click correctly', () => {
const logSpy = jest.spyOn(console, 'log');
const wrapper = shallow(<SampleComponent></SampleComponent>);
const button = wrapper.find('button');
expect(button.text()).toBe('Click Me');
button.simulate('click');
expect(logSpy).toBeCalledWith('hello world');
});
});
我们可以监视 console.log,断言它是否被调用
检查 -
我在使用 React 16.x.x 模拟回调 prop 方法时遇到了类似的问题,酶实例方法 returns null,你可以做的是直接传递 jest.fn() 作为 prop。
示例:
it('should invoke callback with proper data upon checkbox click', () => {
const spyCheckboxClick = jest.fn((id, item) => ({
id,
item,
}))
const component: any = enzyme.mount(
<SectionColumn {...{
...mockProps,
onCheckboxClick: spyCheckboxClick,
}} />
);
expect(spyCheckboxClick).toHaveBeenCalledTimes(0);
// perform click to checkbox
const checkboxComponent = component.find('StyledCheckbox');
const input = checkboxComponent.first().children();
input.simulate('change');
expect(spyCheckboxClick).toHaveBeenCalledTimes(1);
expect(spyCheckboxClick()).toEqual(null)
});
我正在使用 Typescript 和钩子开发一个 React 应用程序,我正在尝试将 Enzyme 与 Jest 结合使用来测试功能组件。我无法使用 jest.spyOn 来测试我的组件中的方法。 jest.spyOn 方法无法正确解析并在悬停时显示以下消息
"Argument of type '"validateBeforeSave"' is not assignable to parameter of type '"context" | "setState" | "forceUpdate" | "render" | "componentDidMount" | "shouldComponentUpdate" | "componentWillUnmount" | "componentDidCatch" | "getSnapshotBeforeUpdate" | ... 6 more ... | "UNSAFE_componentWillUpdate"'.ts(2345)"
我试图将实例转换为 'Any' -
const instance = wrapper.instance() as any;
这当然忽略了编译时的问题,但随后测试抛出组件上不存在函数的运行时错误。
Cannot spy the validateBeforeSave property because it is not a function; undefined given instead
// Some function Component
const SomeComponent = (props: IMyComponentProps) => {
const { classes } = props;
// Component has state
const [count, setCount] = useState(0);
function validateBeforeSave(){
}
function handleClick() {
validateBeforeSave();
.
.
.
}
return (
<div>
<Button>
className="saveBtn"
onClick={handleClick}
</Button>
</div>
);
};
// Unit test
describe('SomeComponent' () => {
it('validates model on button click', () => {
const wrapper = mount(
<MuiThemeProvider theme={theme}>
<SomeComponent/>
</MuiThemeProvider>,
);
const instance = wrapper.instance();
const spy = jest.spyOn(instance, "validateBeforeSave");
wrapper
.find('.saveBtn')
.at(0)
.simulate('click');
expect(spy).toHaveBeenCalledTimes(1);
});
}
我在这里错过了什么? spyOn 如何与函数组件一起工作?
我使用 create-react-app 模板创建了应用程序,它具有测试包的这些依赖项
"devDependencies": {
"ts-jest": "^23.10.3",
"@types/jest": "24.0.9",
"@types/enzyme": "^3.9.1",
"@types/enzyme-adapter-react-16": "^1.0.2",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.11.2",
"enzyme-to-json": "^3.3.5",
}
您的 validateBeforeSave
函数在 SomeComponent
中声明,使其成为无法在外部访问的 closed/private 作用域函数。您可以将该函数作为道具传递,然后您可以创建间谍并将其作为道具值传递到您的测试中,并测试传递的道具函数(间谍)是否被调用
所以你会像这样修改你的函数:
// some validator function
function validateBeforeSave(){
...
}
// Some function Component
const SomeComponent = (props: IMyComponentProps) => {
const { classes, validateBeforeSave } = props;
// Component has state
const [count, setCount] = useState(0);
function handleClick() {
validateBeforeSave();
.
.
.
}
return (
<div>
<Button>
className="saveBtn"
onClick={handleClick}
</Button>
</div>
);
};
并且在你的单元测试中,是这样的:
// Unit test
describe('SomeComponent' () => {
it('validates model on button click', () => {
const validateSpy = jest.fn();
const wrapper = mount(
<MuiThemeProvider theme={theme}>
<SomeComponent validateSpy={validateSpy}/>
</MuiThemeProvider>,
);
const instance = wrapper.instance();
wrapper
.find('.saveBtn')
.at(0)
.simulate('click');
expect(validateSpy).toHaveBeenCalledTimes(1);
});
}
我也遇到了同样的问题 - 我喜欢下面的 -
import * as React from 'react';
const SampleComponent = () => {
const sampleMethod = () => {
console.log('hello world');
};
return <button onClick={sampleMethod} type="button">Click Me</button>;
};
export default SampleComponent;
测试 -
import React from 'react';
import SampleComponent from './';
import { shallow } from 'enzyme';
describe('SampleComponent', () => {
test('should handle click correctly', () => {
const logSpy = jest.spyOn(console, 'log');
const wrapper = shallow(<SampleComponent></SampleComponent>);
const button = wrapper.find('button');
expect(button.text()).toBe('Click Me');
button.simulate('click');
expect(logSpy).toBeCalledWith('hello world');
});
});
我们可以监视 console.log,断言它是否被调用
检查 -
我在使用 React 16.x.x 模拟回调 prop 方法时遇到了类似的问题,酶实例方法 returns null,你可以做的是直接传递 jest.fn() 作为 prop。
示例:
it('should invoke callback with proper data upon checkbox click', () => {
const spyCheckboxClick = jest.fn((id, item) => ({
id,
item,
}))
const component: any = enzyme.mount(
<SectionColumn {...{
...mockProps,
onCheckboxClick: spyCheckboxClick,
}} />
);
expect(spyCheckboxClick).toHaveBeenCalledTimes(0);
// perform click to checkbox
const checkboxComponent = component.find('StyledCheckbox');
const input = checkboxComponent.first().children();
input.simulate('change');
expect(spyCheckboxClick).toHaveBeenCalledTimes(1);
expect(spyCheckboxClick()).toEqual(null)
});