如何测试使用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作为值。我做错了什么,我该如何测试这个功能

问题是,您不是将值作为参数传递给实例函数,而是将其作为表达式传递,因此第二个参数是undefined,这将导致a + b在函数内被求值为NaN。将代码更改为

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

最新更新