簡體   English   中英

用React開玩笑-如何渲染整個組件並進行測試?

[英]Jest with React - How do you render an entire component and test it?

假設我有一個簡單的App組件,並且正在對其進行測試,以查看它是否簡單地返回了一個在屏幕上打印Hello World的div。 為了在測試文件中呈現App,功能助手是什么? 此外,為了測試正在呈現的HTML,在期望調用中調用的函數是什么?

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

describe("App", () => {
  it('prints "HELLO WORLD" to the screen', () => {
     expect(**App??**).**toRENDER??**("HELLO WORLD")
  }
}

謝謝

使用airbnb的庫是一個好習慣。

有一個將兩者一起使用的示例

您的代碼如下所示:

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import {shallow} from 'enzyme'

describe("App", () => {
  it('prints "HELLO WORLD" to the screen', () => {
     const wrapper = shallow(<App />)

     expect(wrapper.text()).toBe("HELLO WORLD")
  }
}

您可能想要查看Jest的快照測試 這就像調用一樣簡單:

import renderer from 'react-test-renderer';

describe('snapshot testing', () => {
  it('should render App', () => {
    const component = renderer.create(<App />);
    const tree = component.toJSON();
    expect(component).toMatchSnapshot();
  });
});

快照文件將存儲在__tests__/__snapshots__文件夾中。 確保將這些快照文件提交到Git存儲庫中,以便其他貢獻者可以對其組件進行快照。

有關如何使用React設置Jest快照測試的更多信息,請參閱此處,因為您將需要安裝一些npm依賴項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM