用打字稿反应,开玩笑tdd

时间:2020-04-26 12:00:09

标签: reactjs typescript jestjs tdd

以打字稿回应,开玩笑

我正在看一些简单的TDD教程,但是我试图使用打字稿,但是这些教程不在打字稿中。

简单的例子是带有标题和计数器的Class组件。

该测试仅测试组件加载不会崩溃,并且单击计数器会增加计数器状态。

我有一个设置功能,可创建浅ri渲染App组件

当我在it语句中调用setup函数时,出现以下错误。

const setup: (state: IState, props?: {}) => ShallowWrapper<any, Readonly<{}>, React.Component<{}, {}, any>>
Expected 1-2 arguments, but got 0.ts(2554)
App.test.tsx(15, 16): An argument for 'state' was not provided.
Peek Problem
No quick fixes available

如何解决此打字稿错误

App.tsx

import React, {Component} from 'react';
import './App.css';

interface IState{
  counter: number
}

interface IProps{

}

class App extends Component<IState, {}> {

  state = {
    counter: 0
  }

  render(){
    return (
      <div data-test='componentApp'>
        <h1 data-test='counter'>The counter is {this.state.counter}</h1>
        <button 
          data-test='button' 
          onClick={() => this.setState({counter: this.state.counter + 1})
          }>Increment Counter</button>
      </div>
    )
  }
}

export default App;

App.text.tsx

import React from 'react';
import App from './App';
import "./setupTests"
import { shallow } from "enzyme";

interface ITest{
  warpper: String,
  val: String
}

interface IState{
  counter: number
}

const setup = (state:IState, props={}) => {
  const wrapper =  shallow(<App {...state} {...props}/>)
  if(state) wrapper.setState(state)
  return wrapper
}

const findByTestAttr = (wrapper:any, val:string) => {
  return wrapper.find(`[data-test="${val}"]`);
}

describe('App Component', () => {

  it('renders without crashing', () => {
    const wrapper = setup() //Error here
    const componentApp = findByTestAttr(wrapper, 'componentApp')
    expect(componentApp.length).toBe(1)
  });

  it('renders incerment button', () => {
    const wrapper = setup() //Error here
    const button = findByTestAttr(wrapper, 'button')
    expect(button.length).toBe(1)
  })

  it('renders counter display', () => {
    const wrapper = setup() //Error here
    const counter = findByTestAttr(wrapper, 'counter') 
    expect(counter.length).toBe(1)
  })

  it('counter starts at 0', () => {
    const wrapper = setup(); //Error here
    const initialCounterState = wrapper.state('counter');
    expect(initialCounterState).toBe(0)
  })

  it('clicking button increments counter display', () => {
    const counterHere = 7
    const wrapper = setup(null, {counterHere})
    const button = findByTestAttr(wrapper, 'button');
    button.simulate('click')
    const counter = findByTestAttr(wrapper, 'counter') 
    expect(counter.text()).toContain(counter+1)
  })

})

1 个答案:

答案 0 :(得分:1)

好吧,此错误并非源于TypeScript,您只是没有在state中传递任何setup。尝试像wrapper一样实例化const wrapper = setup({counter: 0})。附带说明一下,我不鼓励使用shallow,因为它公开了组件的内部(您可以通过调用setState来利用),这是使用它进行渲染的一个讨厌的缺点。而是尝试使用mount