【问题标题】:Check rendered text with enzyme用酶检查呈现的文本
【发布时间】:2020-10-29 20:08:24
【问题描述】:

我正在使用 react-native,我想测试一些功能。

我想检查何时向组件中插入一些文本,例如:“barak walk”。

  1. 它变为“BARAK WALK”。
  2. 当它太长时,将其与“BARAK WALK...”进行比较。

我不知道如何用酶检查它(我准备这次不要使用快照)

代码:

export default ({ text }: Props): JSX.Element => {
  return (
    <View style={styles.box}>
        <Text numberOfLines={1} style={cardText}>
          {text}
        </Text>
      </View>
  );
};

const styles = StyleSheet.create({
  box: {
    height: 160,
    width: 160,
  },
  cardText: {
    color: Colors().ALWAYS_WHITE,
    textAlign: 'center',
    fontSize: 12,
    fontFamily: AleckFonts.SANS_MEDIUM,
    letterSpacing: 0.4,
    lineHeight: 15,
    padding: 6,
    paddingLeft: 20,
    paddingRight: 20,
    textTransform: 'uppercase',
  },
});

我试过这个,但它没有呈现文本:

test('Should check if text shown as expected', () => {
  const receivedText = 'barak walk';
  const expectedText = 'BARAK WALK';
  const wrapper = shallow(<Card text={receivedText} />);
  const textView = wrapper.find(Text).children();
  expect(textView.text()).toBe(expectedText);
});

【问题讨论】:

  • 你能检查一下textView 的值是多少吗?也许如果你这样做expect(textView).toBe(expectedText);,它可能会起作用..
  • @nishkaush,它不起作用:/
  • 算出textView的值是否幸运?
  • @nishkaush,不,我收到此错误预期:“以旧换新”收到:“以旧换新”
  • 你能不能试试-wrapper.find(Text).children,不要把children作为函数调用,只是引用它

标签: react-native jestjs enzyme


【解决方案1】:

可以尝试的几件事:

(1)Don't use children at all

  const textView = wrapper.find(Text);  // <----take out children prop
  expect(textView.text()).to.equal(expectedText);

另外因为你使用 CSS 来改变文本的大小写,它仍然会呈现为小写。

示例 - barak walk 呈现为 barak walk 但由于 css 样式,它以全大写形式显示给您。

所以,在你的断言中,如果你这样写你的原始测试,它应该通过:

  const textView = wrapper.find(Text); // <--- try
  expect(textView.text()).toBe(receivedText); //<---- receivedText is gona be lowercase

这是因为receivedText 将全部小写。

字符串太长时在末尾添加...

function handleLongString(str, desiredLength){
   return str.length > desiredLength ? str.slice(0,desiredLength) + "..." : str;
}

然后你可以像这样在你的代码中使用它:


<Text>{ handleLongString(text) }</Text>

【讨论】:

  • 还是不行,1.you can't call 'text()', 2. I get Expected value: "TRADE-IN ELIGIBLE" 收到函数:[Function children]
  • 你可以尝试props().children,而不是按照我回答中的3方法
  • “TextProps”类型上不存在属性“children”
  • 最后一次,你能不能也试试第四种方法..
  • 谢谢兄弟,但我仍然得到“'TextProps'类型上不存在属性'children'”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
  • 2017-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多