簡體   English   中英

sinon spy測試帶樣式組件的onClick react組件

[英]sinon spy testing onClick react component with styled-components

我正在使用sinon來測試react組件,以確認函數已觸發onClick

我正在使用styled-components因此很難確定要單擊的元素的目標。

我看到以下錯誤:

方法“模擬”僅旨在在單個節點上運行。 找到0個。

我的反應代碼如下所示:

import React, { Component } from 'react'
import styled from 'styled-components'
import PropTypes from 'prop-types'

class Button extends Component {

  pressNumber = () => {
    this.props.updateNumber(this.props.number)
  }

  render() {

    return (
      <ButtonContainer 
        onClick={ this.pressNumber }
      >
        <Number>{ this.props.number }</Number>
      </ButtonContainer>
    )
  }

}

const ButtonContainer = styled.div`
  height: 60px;
  width: 60px;
`

const Number = styled.div`
  color: #fff;
  font-size: 26px;
  font-weight: 300;
`

然后,我的測試如下所示:

import { expect } from 'chai'
import { shallow, mount } from 'enzyme'
import sinon from 'sinon'
import React from 'react'
import Button from './index'

describe('Button', () => {

  let wrapper
  const pressNumber = () => {}

  beforeEach(() => {
    wrapper = mount(
      <Button 
        number={1} 
        pressNumber={ pressNumber } 
      />
    )
  })

  it('should call the update pin prop when click is simulated', () => {
    const updatePinClick = sinon.spy();
    wrapper.find('ButtonContainer').simulate('click')
    expect(updatePinClick.calledOnce).to.be.true
  })

})

任何人都可以看到我在這里做錯了什么,以及是否有與我使用樣式化組件不同的方法。

我看到以下錯誤

方法“模擬”僅旨在在單個節點上運行。 找到0個。

(公開:我是酶的維持者)

您的間諜是updatePinClick ,但您沒有將其傳遞到任何地方,因此無法使用。 此外, Button不使用pressNumber道具。

首先,我建議以下一般性提示:

  1. 避免使用.simulate如果您要調用道具,請直接執行,例如.prop('onClick')()
  2. 不要在beforeEach定義包裝器-在測試中,最好重復自己,尤其是要使用的jsx。
  3. 避免將字符串傳遞給.find ; 導出要查找的組件,然后通過引用查找它,就不那么容易了。
  4. 避免使用noop匹配器-即,不會以函數結尾的東西,例如.to.be.true 這是因為您可以輕松地輸入錯誤,並且會以靜默方式失敗expect(object).to.be.yogurt; 會愉快地通過,即使這不是有效的匹配器。
  5. 對於所有測試,最好選擇shallow 僅在需要使用引用或測試componentDidMount或其他僅瀏覽器的代碼時才使用mount

具體來說,請嘗試以下操作:

import { expect } from 'chai'
import { shallow, mount } from 'enzyme'
import sinon from 'sinon'
import React from 'react'
import Button from './index'

describe('Button', () => {
  it('should call the update pin prop when click is simulated', () => {
    const updatePinClick = sinon.spy();
    const wrapper = shallow(
      <Button 
        number={1} 
        updateNumber={updatePinClick} 
      />
    );
    wrapper.find('ButtonContainer').prop('onClick')();
    expect(updatePinClick).to.have.property('callCount', 1);
    expect(updatePinClick.calledWith(1)).to.equal(true);
  });
})

您可能應該遵循LJHarb的建議,但是只是要解決該錯誤:

方法“模擬”僅旨在在單個節點上運行。 找到0個。

使用mount渲染<Button/>將渲染它及其所有子級(及其子級,依此類推)。 結果, <ButtonContainer/><Number/>已呈現到<div> 因此,搜索ButtonContainer得出0個結果。

暫無
暫無

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

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