首页 > 解决方案 > 如何测试使用 instance() 方法访问的函数的值

问题描述

我有一个像下面这样的反应组件

import React, { Component } from 'react'

import { ActionWrapper } from 'components/Wrappers'

import { P } from 'components/Text'

class TestStock extends Component {
  total = (a, b) => {
    let totValue = 0
    totValue = a + b
    return totValue
  }

  render() {
    return (
      <ActionWrapper
        title="In stock"
        description={'Manage your in stock items'}
      >
        <P>Total is {this.totValue}</P>
      </ActionWrapper>
    )
  }
}

export default TestStock

我写了一个测试,测试下面的总功能

 describe('total function in the stock', () => {
  const wrapper = shallow(<Stock />)
  const value = wrapper.instance().total(5 + 7)

  test('for total value calculation', () => {
    expect(value).toBe(6)
  })

  test('for total less or equal to 10 ', () => {
    expect(value).toBeLessThanOrEqual(10)
  })
})

但是测试失败了,因为我收到了 Nan 作为值。我做错了什么,我该如何测试这个功能

标签: reactjsjestjs

解决方案


问题是,不是将值作为参数传递给实例函数,而是将 then 作为表达式传递,因此第二个参数会undefined导致在函数内部a + b进行评估NaN。将您的代码更改为

const value = wrapper.instance().total(5, 7)

推荐阅读