【问题标题】:Expect toContain text from a set of values in jest,enzyme with React期望在玩笑中包含一组值中的文本,用 React 加酶
【发布时间】:2018-07-21 17:57:33
【问题描述】:

我下面的测试有效,

let output = mount(story);
      expect(output.text()).toContain('Superman');

但我什至需要允许蝙蝠侠和蜘蛛侠通过: 我需要检查 output.text() 是否有 -> ['超人','蝙蝠侠','蜘蛛侠']

不能用

expect(output.text()).toContain(['Superman','Batman','Spiderman']);

output.text() 将包含“超人是最好的”或“蜘蛛侠是最好的”

【问题讨论】:

    标签: reactjs jasmine tdd jestjs enzyme


    【解决方案1】:

    这样的事情对你来说是更好的答案:

    expect(output.text()).toEqual(expect.stringMatching(/^(Batman|Superman|Spiderman)/));
    

    【讨论】:

      【解决方案2】:

      You can add your own matcher 而不是toContain

      expect.extend({
        toContainHero(text) {
          let pass = false;
          const heroes = ['Superman','Batman','Spiderman'];
          heroes.forEach((hero) => {
            pass = text.indexOf(hero) !== -1;
          })
          if (pass) {
            return {
              message: () =>
                `expected hero to be found`,
              pass: true,
            };
          } else {
            return {
              message: () => `expected hero to be not found`,
              pass: false,
            };
          }
        },
      });
      

      然后做:

      expect(output.text()).toContainHero();
      

      【讨论】:

      • 谢谢,只要确保 pass 一次 true 不会被覆盖 ` toContainHero(text) { let pass = false; const hero = ['超人','蝙蝠侠','蜘蛛侠']; hero.forEach((hero) => { ( pass = pass ?pass : text.indexOf(hero) !== -1); }) if (pass) { return { message: () => expected hero to be found, pass : 真的, }; } else { 返回 { 消息:() => expected hero to be not found,通过:假,}; } }, });期望(输出。文本())。toContainHero(); `
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 2019-01-16
      • 2022-08-17
      • 2017-09-26
      • 1970-01-01
      • 2019-08-05
      相关资源
      最近更新 更多