reactjs - 如何测试使用 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 作为值。我做错了什么,我该如何测试这个功能
解决方案
问题是,不是将值作为参数传递给实例函数,而是将 then 作为表达式传递,因此第二个参数会undefined
导致在函数内部a + b
进行评估NaN
。将您的代码更改为
const value = wrapper.instance().total(5, 7)
推荐阅读
- apache-kafka-streams - 如何为 Kafka 流创建的状态存储设置保留期
- sorting - 如何将自动排序的空白行发送到底部?
- python - 将数组中的数组与两个数字相乘
- python - 人口增长:根据年龄组分组向数据添加行(添加新的“人”)
- javascript - 使用 JS 制作宾果游戏
- java - 使用java复制节点内的所有元素,但不复制XML中的节点标记
- javascript - 如何使用映射函数访问嵌套数组中的键?
- python - 构建 python 模块,使其可以在带有和不带有 -m 开关的命令行中运行
- r - 调用以网状为源的函数时,R 因段错误而崩溃
- python - 如何测试字符串包含列表中的元素并通过 Pandas 将目标元素分配给另一列