React, Jest tdd with typescript.

问题描述 投票:0回答:1

React, Jest tdd with typescript.

嗨,你好

我在看一些简单的TDD教程,但我想用typescript,但教程不是用typescript。

简单的例子是有一个头和一个计数器的类组件。

测试只是测试组件加载时没有崩溃,点击计数器会增加计数器的状态。

我有一个设置函数,创建一个浅层的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)
  })

})
reactjs typescript jestjs tdd
1个回答
1
投票

好吧,这个错误并不是源于TypeScript,你只是没有传递任何的代码。statesetup. 尝试实例化 wrapper 喜欢 const wrapper = setup({counter: 0}). 顺便说一句,我不鼓励使用 shallow 因为它暴露了组件的内部(您通过调用 setState),这是用它来渲染的一个讨厌的缺点。相反,可以尝试使用 mount.

© www.soinside.com 2019 - 2024. All rights reserved.