简体   繁体   English

JEST 测试反应组件

[英]JEST to test react components

I am following the tutorial on jest on how to test my component, and am wondering if I am missing anything.我正在关注关于如何测试我的组件的开玩笑教程,并且想知道我是否遗漏了任何东西。 I am trying to test my weatherApp.js whose sole purpose is to display information from my TemperatureData.js with a color from my colorize.js我正在尝试测试我的weatherApp.js ,其唯一目的是使用来自我的colorize.js的颜色显示来自我的TemperatureData.js的信息

export default class Weather extends React.Component {
    constructor(props) {
        super(props);
        this.state = {temp: undefined}}
    componentDidMount() {temperatureData().then(temp => {this.setState({temp: temp})})
    }
    render() {
        const temperature = this.state.temp;
        return <>{this.state.temp === undefined ?<somegraph />:<p style={{ color: colorize(temperature) }} id="temperature">{temperature}</p>}</>
    }
}

Here is what I have to test this application, I'm not sure if i need to test anything else or what else im missing, any input appreciated.这是我必须测试此应用程序的内容,我不确定是否需要测试其他任何内容或我还缺少什么,感谢任何输入。

describe("<WeatherApp> component test", () => {
  test("displays data from temperature data", async () => {
    const mockedTemp = "something irrelevant";
    temperatureData.mockImplementation(() => {
      return Promise.resolve(mockedTemp)
    })
    const weatherComponent = render(<WeatherApp />);
    expect(temperatureData).toHaveBeenCalled()
    await wait(() => {
      const paragraph = weatherComponent.getByText(mockedTemp)
      //console.log(paragraph)
      expect(paragraph).toBeInTheDocument()
      expect(paragraph).toBeDefined()
    });
  })
})

I am not sure if i should test to see if the correct color is returned based on my temperature input as i have a separate unit test for my colorize file...我不确定我是否应该测试是否根据我的温度输入返回正确的颜色,因为我对我的着色文件有一个单独的单元测试......

You can configure jest to report test coverage information, by adding --coverage=true option to your test command line:您可以通过在测试命令行中添加--coverage=true选项来配置jest以报告测试覆盖率信息:

jest --coverage=true

Test coverage will give you a first hint of what's missing in your tests.测试覆盖率将首先提示您测试中缺少什么。

For example, if you forgot to test a conditional rendering based on a ternary operator (which is the case here, you don't test that if this.state.temp is undefined , <somegraph /> should be displayed), the coverage report ( something like this ) will give you the uncovered lines , which is a great indicator to know if you forgot to test some basic logic of your component.例如,如果您忘记测试基于三元运算符的条件渲染(这里就是这种情况,您不测试如果this.state.tempundefined ,应该显示<somegraph /> ),覆盖率报告( 类似这样的东西)会给你未覆盖的行,这是一个很好的指标,可以知道你是否忘记测试你的组件的一些基本逻辑。

However, test coverage might not be aware of some more subtil logic, like side effects or css styling etc.. Sometimes you'll need to think a bit further for testing more specific logic in your components.但是,测试覆盖率可能不知道一些更微妙的逻辑,例如副作用或 css 样式等。有时您需要进一步思考以测试组件中更具体的逻辑。

I suggest you start by making sure you don't have uncovered lines by looking at coverage report.我建议您首先通过查看覆盖率报告来确保您没有未发现的线路。 Hope it will help !希望它会有所帮助!

Whether your unit-test is sufficient depends on what you define as the critical criteria for your component.您的单元测试是否足够取决于您定义的组件的关键标准。 If it is critically important to ensure the temperature is displayed in the correct color, you should probably test that.如果确保温度以正确的颜色显示至关重要,您可能应该对其进行测试。 However, as you said, you have a separate test for the colorize function, so that may be enough.但是,正如您所说,您对着色 function 有单独的测试,所以这可能就足够了。 If that gives you confidence that it will work there is no need to test it again in the weatherApp.js如果这让您确信它会起作用,则无需在weatherApp.js再次测试它

Those decisions are relatively subjective, and one of the reasons unit-testing is challenging - there are relatively few prescriptive answers as far as what to test.这些决定是相对主观的,也是单元测试具有挑战性的原因之一——关于要测试什么的规定性答案相对较少。 For some better guidance, this is a pretty good read on the subject .为了获得更好的指导,这是一个很好的阅读主题

There are, however, ways of structuring your components that facilitate easier unit testing, and in that regard I have a suggestion for changing the way your component is built since really, I think, what you care about is that:然而,有一些构建组件的方法有助于更轻松地进行单元测试,在这方面,我有一个改变组件构建方式的建议,因为我认为,你真正关心的是:

  • The WeatherApp component displays colorized temperature data WeatherApp组件显示彩色温度数据

Right?正确的? You don't really care that it calls the API...the data could come from anywhere.并不关心它调用 API ......数据可能来自任何地方。 And you don't really care that it calls the colorize function...only that there is a color applied.而且您并不真正关心它调用 colorize function ......只是应用了颜色。 Testing those details only makes your unit-test brittle, meaning for instance that you will have to update the unit-test definition if your API changes.测试这些细节只会让你的单元测试变得脆弱,这意味着如果你的 API 发生变化,你将不得不更新单元测试定义。

Instead, make the WeatherApp component stateless and presentational.相反,让WeatherApp组件无状态且具有展示性。 Use a parent component to handle:使用父组件来处理:

  1. Calling the API调用 API
  2. Calculating the color计算颜色
  3. Rendering the WeatherApp渲染WeatherApp
class ParentComponent extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        temp: undefined,
        color: undefined,
      }
    }

    componentDidMount() {
      temperatureData().then(temp => {
        this.setState({
          temp: temp
          color: colorize(temp)
        })
      })
    }

  render(
    return (
      <WeatherApp temp={this.state.temp} color={this.state.color} />
    )
  )
}

Then your test looks something like this instead:然后你的测试看起来像这样:

describe("<WeatherApp> component test", () => {
  test("displays data from temperature data", () => {
    const mockedTemp = "something irrelevant";

    const weatherComponent = render(<WeatherApp temp={mockedTemp} />);

    const paragraph = weatherComponent.getByText(mockedTemp)
    expect(paragraph).toBeInTheDocument()
  })
})

You could include the color there in the test, or not...up to you.您可以在测试中包含颜色,或者不...由您决定。

Since you can test all 3 units (temp/color/weatherApp) that make up the parent component separately, you can be relatively confident that the parent component will work.由于您可以分别测试构成父组件的所有 3 units (温度/颜色/天气应用程序),因此您可以相对确信父组件可以正常工作。 You also have an added bonus of not needing to write any asynchronous code in the unit-test.您还有一个额外的好处,即不需要在单元测试中编写任何异步代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM