簡體   English   中英

存根讀取單元測試與酶和玩笑反應

[英]stub fetch unit test react with enzyme and jest

我正在嘗試使用酶和玩笑來對API調用進行響應。

我的React Component代碼如下所示。 這很完美。

async componentDidMount() {
    try {
      const res = await fetch(FETCH_ENDPOINT)
        if(res.ok) {
          const data = await res.json()
          this.setState({
            players: data.players,
            error: false
          });
        } else {
          throw new Error('Something went wrong');
        }
    } catch (error) {
      this.setState({
        error: true,
      })
    }
  }

我正在嘗試模擬響應並測試api調用的成功和失敗。 我的測試代碼如下所示,並且它從未使用api的響應響應來更新this.state.players 我覺得我在犯一個簡單的錯誤。 誰能看到下面的代碼有什么問題嗎? 它只是顯示為長度為0,而不是該行的2

也許這與我的componentDidMount api調用中有2個諾言有關,但是我的spec文件中只有一個諾言嗎?

expect(renderedComponent.state('players').length).toEqual(2)

import React, { Component } from 'react';
import App from './App';
import { shallow } from 'enzyme'

const result = {
    'players': [
      {
        'firstname': 'Robbie',
        'lastname': 'Keane',
      },
      {
        'firstname': 'Alan',
        'lastname': 'Shearer',
      }
    ]
  }

describe('App', () => {
  describe('componentDidMount', () => {
    it('sets the state componentDidMount', async () => {
      window.fetch = jest.fn().mockImplementation(() => ({
        status: 200,
        ok: true,
        json: () => new Promise((resolve, reject) => {
          resolve({
            result: {
             'players': [
               { 'firstname': 'Robbie', 'lastname': 'Keane' },
               { 'firstname': 'Alan', 'lastname': 'Shearer' }
            ]
          })
        })
      }))

      const renderedComponent = await shallow(<App />)
      await renderedComponent.update()
      expect(renderedComponent.state('players').length).toEqual(2)
    })
  })
})

如前所述,您的測試文件中還需要一個Promise。 另外,您應該從json對象中刪除result屬性。 這是一個有效的測試代碼:

window.fetch = jest.fn().mockImplementation(() => {
    return new Promise((resolve, reject) => {
        resolve({
            status: 200,
            ok: true,
            json: () => new Promise((resolve, reject) => {
                resolve({
                    'players': [
                        { 'firstname': 'Robbie', 'lastname': 'Keane' },
                        { 'firstname': 'Alan', 'lastname': 'Shearer' }
                    ]
                });
            })
        });
    });
})

測試組件:

import React from 'react';

const TEST = "test";

class Test extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
        players: [],
        error: false,
    };
  }
  async componentDidMount() {
    try {
      const res = await fetch(TEST)
      if(res.ok) {
        const data = await res.json()
        this.setState({
          players: data.players,
          error: false,
        });
      } else {
        throw new Error('Something went wrong');
      }
    } catch (error) {
      this.setState({
        error: true,
      });
    }
  }
  render() {
    return (<div>Hello world</div>);
  }
}

export default Test;

暫無
暫無

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

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