reactjs - 如何在 Typescript 的功能组件中模拟一个函数?
问题描述
试图弄清楚如何模拟功能组件 Typescript React 中的函数。这是代码...
HeaderBar.tsx
const HeaderBar: React.FC<RouteComponentProps<any>> = (props: any) => {
const search = e => {
console.log(e);
};
};
HeaderBar.test.tsx
:
import HeaderBar from './HeaderBar';
it('mocks the search function', () => {
const wrapper = shallow(<HeaderBar />);
const mock = jest.spyOn(HeaderBar, 'search');
})
我收到以下错误:
无法窥探搜索属性,因为它不是函数;取而代之的是未定义。
我认为这是因为我要测试的功能在另一个功能(即功能组件)内部。我没有使用类,所以我想知道如何模拟这个函数?
解决方案
您不能模拟 SFC 中定义的函数。而且,我们不应该测试函数的实现细节。我们应该测试 React 组件的行为。这是测试 React Component 的测试背景和策略。
因此,您的示例代码的单元测试是:
HeaderBar.tsx
:
import React from 'react';
const HeaderBar = (props: any) => {
const search = e => {
console.log(e);
};
return <div onClick={search}></div>;
};
export default HeaderBar;
HeaderBar.test.tsx
:
import React from 'react';
import HeaderBar from './HeaderBar';
import { shallow } from 'enzyme';
it('mocks the search function', () => {
const logSpy = jest.spyOn(console, 'log');
const wrapper = shallow(<HeaderBar />);
const mEvent = { target: 'fake target' };
wrapper.find('div').simulate('click', mEvent);
expect(logSpy).toBeCalledWith(mEvent);
});
我们可以监视console.log
并测试它是否会被调用。如果setState
您的函数中有,您应该使用wrapper.state()
测试状态,将其断言为您的预期状态。
100% 覆盖率的单元测试:
PASS src/stackoverflow/57154476/HeaderBar.test.tsx
✓ mocks the search function (16ms)
console.log node_modules/jest-mock/build/index.js:860
{ target: 'fake target' }
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
HeaderBar.tsx | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.506s, estimated 9s
源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57154476
推荐阅读
- angular - 使用 AngularFirestore 和 firebase 的“ERROR TypeError: Object(...) is not a function”
- r - 如果满足条件,则复制前一行
- sql - SQL Server 存储过程 - 如果存在则跳过,否则插入
- sql - 例如,高于特定价值(500 美元)的商品的百分比?
- android - Bundle 是可以为空的,即使我没有这样声明它
- regex - unix 找到带有模式的正则表达式,而不是以另一个模式结尾
- react-native - 图像调整大小封面 - 保持图像的左上角
- python-2.7 - 单位转换器,用户在公里或英里之间选择
- mysql - 如何为友谊关系创建sql(mysql)?
- c# - 如何从 Xamarin android 资源中的 strings.xml 正确访问字符串资源?