簡體   English   中英

用 Jest 進行反應測試:解構分配不起作用

[英]React testing with Jest : Destructuring assignment not working

我正在嘗試使用 Jest 和 Enzyme 測試反應組件。 我的componentDidMount方法/函數

Real.jsx

// some code

class MyComponent extends React.Component {


    componentDidMount() {
      setTimeout (() => {
        const { formVals : { eName, eSal }, changeVal } = this.props
        console.log("changeVal function" + changeVal)
        changeVal(someparam , someparam2)
      }, 1000)
    }

// some more functions 

}

export default MyComponent

我的測試代碼就像

import MyComponent from '../../components/Real' //Real.jsx

    jest.useFakeTimers();
    test('test componentDidMount', () => {
      var props = {
        formVals: {
          eName: 123,
          eSal: 10000
        },
        changeVal: (x, y) => console.log(x)
      }
    
      var component = shallow <MyComponent {...props}/>
      jest.runAllTimers(); // getting coverage for setTimeOut
      component.update();  // getting coverage for setTimeOut
    }) 

但是我將 changeVal 的值設為 undefined,這意味着解構賦值不起作用。

請幫助解決在這種情況下可能出現的問題。

這里是 go。

const { 
  formVals: { eName, eSal },
  changeVal
} = this.props;

嘗試這個。

     const { formVals : { eName, eSal }, changeVal } = this.props

更改const { formVals { eName, eSal }, changeVal } = this.props

const { formVals, changeVal } = this.props;
const { eName, eSal } = formVals;

或者

const { formVals: { eName, eSal }, changeVal } = this.props

更新:嘗試使用片段重現問題。 唯一的改變是我必須刪除; 在 console.log 末尾以避免錯誤。

 var props = { formVals: { eName: 123, eSal: 10000, }, changeVal: (x, y) => console.log(x) }; const { formVals: { eName, eSal }, changeVal, } = props; changeVal("print this", "hello");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM