首页 > 解决方案 > 使用 JEST 在 ReactJS 单元测试中期望返回 HTML

问题描述

我正在尝试对该功能进行单元测试

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));
  });
});

标签: reactjsjestjs

解决方案


就想看到整个html返回而言,我认为你应该去使用snapshot测试。

toMatchSnapshot()通常,您会生成 html 内容并存储为文件,您可以使用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>
`;


推荐阅读