对于测试,我使用jest和react-test-renderer。测试应该很简单,但是我很难找到合适的例子。我尝试做类似的事情(通常我将功能保存在单独的文件中):
utils.js
export const childFunction = () => 'something';
const parentFunction = () => childFunction();
export default parentFunction;
Run Code Online (Sandbox Code Playgroud)
utils.test.js
import parentFunction from './utils.js';
it('childFunction should be called', () => {
const childFunction = jest.fn();
parentFunction();
expect(childFunction).toBeCalled();
})
Run Code Online (Sandbox Code Playgroud)
片段const childFunction = jest.fn(); 绝对行不通。调用时,parentFunction的主体仅关心其自身的作用域。但是,如果我导入childFunction并执行jest.mock(childFunction),它也将不起作用,因为jest.mock需要一个字符串,一个模块的url,而不是函数本身。
上面的示例不起作用,我正在寻找替代方法。但是,在使用ShallowRenderer渲染组件后,此方法有效。而且我想通过嵌套在另一个函数中的函数来实现类似的行为。
class Component extends React.Component {
componentDidMount() {parentFunction()}
render() {...}
}
const renderer = new ShallowRenderer();
describe("testing parentFunction", () => {
renderer.render(<Component/>);
it("parentFunction should be called", () => {
expect(parentFunction).toBeCalled();
});
});
Run Code Online (Sandbox Code Playgroud) 我使用 React 16 和 Typescript 3。我创建一个组件,根据属性是否设置返回按钮或链接。该组件可以获取to或onClick属性,但不能同时获取两者。
我在 TypeScript 存储库上发现了问题,它准确地描述了我的问题,并且似乎在 2.2 版本中修复了,但以某种奇怪的方式,它不起作用。
为此,我创建了接口并按如下方式使用它们:
interface GeneralProps {/* whatever here, it works */}
interface LinkProps extends GeneralProps { to: string }
interface ButtonProps extends GeneralProps {
onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void
// onClick might be as well undefined
}
function Button (props: LinkProps | ButtonProps): JSX.Element {
const Component: AnyStyledComponent = props.to ? Link : Button
return (
<Component to={props.to} onClick={props.onClick}>
{props.children}
</Component>
)
} …Run Code Online (Sandbox Code Playgroud)