簡體   English   中英

你如何測試 React 組件中的基本方法?

[英]How do you test a basic method in a React Component?

我有一個 React 組件,它有一個簡單的輸入表單和按鈕來輸入電子郵件。 我的代碼庫使用 Jest 進行了單元測試(使用 jest-dom 和 @testing-library/react)以及使用 Cypress 進行了集成測試。

我想在一個名為 ContactBox 的 React 組件上為這個簡單的方法編寫一個單元測試。

您會注意到這個處理程序只是使用onSubmit={this.addEmail}附加到表單元素

addEmail(event) {
    event.stopPropagation()
    event.preventDefault()
    let email = this.emailCaptureRef.current.value

    let  domain = 'https://somedomain.com/'

    fetch(domain + 'newsletter/sign_up', {
      method: "POST",
      body: JSON.stringify({_method: 'POST', email: email})
    })
      .then((response) => {
        if (response.status >= 400) {

        }
        return response.json().then((result) => {
          this.setState({email_box_used: true})
        })
      })
  }

有沒有什么好方法可以用 Jest 測試這個?

我想我很好奇的是 Jest 文檔都顯示了渲染 React 組件的各種策略,是否可以在組件上對該方法進行單元測試而不必渲染?

React Component 類只是 JavaScript 類,我們可以直接使用Class.prototype.method測試類的方法,無需使用 React 相關的測試工具。

index.tsx

import React, { Component } from 'react';

class ContactBox extends Component {
  emailCaptureRef;
  constructor(props) {
    super(props);
    this.state = { email_box_used: false };
  }

  addEmail(event) {
    event.stopPropagation();
    event.preventDefault();
    const email = this.emailCaptureRef.current.value;
    const domain = 'https://somedomain.com/';

    fetch(domain + 'newsletter/sign_up', {
      method: 'POST',
      body: JSON.stringify({ _method: 'POST', email }),
    }).then((response) => {
      return response.json().then((result) => {
        this.setState({ email_box_used: true });
      });
    });
  }
  render() {
    return (
      <div>
        <form onSubmit={this.addEmail}></form>
      </div>
    );
  }
}

export default ContactBox;

index.test.tsx

import ContactBox from './';

const whenStable = () => new Promise((resolve) => setTimeout(resolve));

describe('60403489', () => {
  it('should add email', async () => {
    const mResponse = { json: jest.fn().mockResolvedValueOnce({}) };
    const mFetch = jest.fn().mockResolvedValueOnce(mResponse);
    (global as any).fetch = mFetch;
    const setStateSpy = jest.spyOn(ContactBox.prototype, 'setState').mockReturnValueOnce();
    const mEvent = { stopPropagation: jest.fn(), preventDefault: jest.fn() };
    ContactBox.prototype.emailCaptureRef = { current: { value: 'example@gmail.com' } };
    ContactBox.prototype.addEmail(mEvent);
    await whenStable();
    expect(mFetch).toBeCalledWith('https://somedomain.com/newsletter/sign_up', {
      method: 'POST',
      body: JSON.stringify({ _method: 'POST', email: 'example@gmail.com' }),
    });
    expect(mResponse.json).toBeCalledTimes(1);
    expect(setStateSpy).toBeCalledWith({ email_box_used: true });
  });
});

帶有覆蓋率報告的單元測試結果:

 PASS  stackoverflow/60403489/index.test.tsx
  60403489
    ✓ should add email (8ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |   83.33 |        0 |   66.67 |   81.25 |                   
 index.tsx |   83.33 |        0 |   66.67 |   81.25 | 6,7,26            
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.822s, estimated 10s

源代碼: https : //github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60403489

暫無
暫無

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

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