Jest + Typescript 如何测试 React 组件中的方法?

cbl*_*bll 2 typescript reactjs jestjs

我正在使用 Typescript/React 创建 .tsx 组件。我想对 React 组件中的方法进行一些单元测试。说:

export default class SomeComponent extends React.Component<undefined, SomeComponentState> {

    someMethod = (string: someInput) => {
        return someInput + someInput;
    }
    render () .. // etc
}
Run Code Online (Sandbox Code Playgroud)

在 SomeComponent.test.tsx 文件中,如何导入并测试 someMethod,而不是整个组件本身?

我试过了:

import {someMethod} from "./someComponent"; 
Run Code Online (Sandbox Code Playgroud)

虽然没有运气 - 它似乎不可调用,并且会抛出 TS 错误:“组件没有导出成员 someMethod”

Way*_*neC 5

Its a member of the class, so you need an instance to test it. You can't import it directly. If it doesn't need to access to anything else on the instance, you can extract it as a seperate function and export it.

Alternatively using enzyme you could test it with something like this: import {shallow} from 'enzyme';

it('.....', () => {
    const wrapper = shallow(<SomeComponent />);
    (wrapper.instance() as SomeComponent).someMethod('someValue');
})
Run Code Online (Sandbox Code Playgroud)