背景 在线测试react-redux高阶组件有很多例子,例如:使用connect()反应组件。但是,它们都在ES6中。我了解结构并能够在这些文档或示例的帮助下运行测试。
问题 当我尝试使用JS代码并将其转换为Typescritpt时,我开始遇到类型问题。不确定如何在打字稿
中完成我尝试测试的组件是AspNetCore React-Redux yoman脚手架中的Counter组件
Counter.tsx
import * as React from 'react';
import { Link, RouteComponentProps } from 'react-router-dom';
import { connect } from 'react-redux';
import { ApplicationState } from '../store';
import * as CounterStore from '../store/Counter';
import * as WeatherForecasts from '../store/WeatherForecasts';
type CounterProps =
CounterStore.CounterState
& typeof CounterStore.actionCreators
& RouteComponentProps<{}>;
export class Counter extends React.Component<CounterProps, {}> {
public render() {
return <div>
<h1>Counter</h1>
<p>This is a simple example of a React component.</p>
<p>Current count: <strong>{ this.props.count }</strong></p>
<button onClick={
() => { this.props.increment() }
}>Increment</button>
</div>;
}
}
export default connect(
(state: ApplicationState) => state.counter,
CounterStore.actionCreators
)(Counter) as typeof Counter;
Counter.spec.js
import { Counter} from '../../ClientApp/components/Counter;
import * as Provider from 'react-redux';
import configureMockStore from 'redux-mock-store';
import * as store from '../../ClientApp/store';
import { shallow, mount } from 'enzyme';
declare var describe, beforeEach, it, expect, state, stub;
describe('Counter', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<Provider store={store}>
<Counter />
</Provider>
)
});
it('render Counter', () => {
expect(wrapper.length).toEqual(1)
});
});
错误消息
[ts] JSX element type 'Provider' does not have any construct or call signatures.
[ts] 'React' refers to a UMD global, but the current file is a module. Consider adding an import instead
[ts]
Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Login> & Readonly<{ children?: ReactNode; }> & Rea...'.
Type '{}' is not assignable to type 'Readonly<UserProps>'.
Property 'loggedIn' is missing in type '{}'.
问题
如何摆脱这些错误消息
答案 0 :(得分:1)
您忘记了在规范文件中导入React:
import * as React from 'react' // -------------------------------> THIS LINE
import { Counter} from '../../ClientApp/components/Counter;
import * as Provider from 'react-redux';
import configureMockStore from 'redux-mock-store';
import * as store from '../../ClientApp/store';
import { shallow, mount } from 'enzyme';
declare var describe, beforeEach, it, expect, state, stub;
describe('Counter', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<Provider store={store}>
<Counter />
</Provider>
)
});
it('render Counter', () => {
expect(wrapper.length).toEqual(1)
});
});