【问题标题】:Expect return HTML in ReactJS unit testing using JEST使用 JEST 在 ReactJS 单元测试中期望返回 HTML
【发布时间】:2020-11-26 01:37:51
【问题描述】:

我正在尝试对这个函数进行单元测试

export const scoreText = score => {
  if (score < 1.0) {
    return <span style={{ color: '#fd7878' }}>{score}</span>;
  }

  if (score >= 1.0 && score <= 1.5) {
    return <span style={{ color: '#fd7878' }}>{score}</span>;
  }

  if ((score >= 1.51 && score <= 2.49) || (score >= 2.5 && score <= 3.0)) {
    return <span style={{ color: '#2fcc71' }}>{score}</span>;
  }

  return score;
};

这是我现在的代码。如何进行单元测试以期望返回 HTML 代码?

describe('scoreText', () => {
  it('score less than 1.0', () => {
    expect(scoreText(0).toBeLessThan(1.0));
  });
  it('score not less than or equal to 1.0 greater than or equal to 1.5', () => {
    expect(scoreText(1.2).toBeLessThanOrEqual(1.5));
  });
  it('score not less than or equal to 1.5 greater than or equal to 2.49', () => {
    expect(scoreText(2.0).toBeLessThanOrEqual(2.49));
  });
});

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:

    就希望看到整个html 返回而言,我认为您应该使用snapshot 测试。

    通常,您会生成 html 内容并存储为文件,您可以使用 toMatchSnapshot() api 检查它是否正确:

    it('score less than 1.0', () => {
      expect(scoreText(0)).toMatchSnapshot();
    });
    

    然后你会看到快照如下:

    exports[`scoreText score less than 1.0 1`] = `
    <span
      style={
        Object {
          "color": "#fd7878",
        }
      }
    >
      0
    </span>
    `;
    
    

    【讨论】:

      【解决方案2】:

      需要使用toContain:

        expect(scoreText(1.2).toContain('<'));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-14
        • 1970-01-01
        • 2018-03-25
        • 1970-01-01
        • 2019-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多