简体   繁体   English

如何使用Jest测试ES6 fetch方法

[英]How to test the ES6 fetch method with Jest

I'm trying to write test case for my ES6 app using Jest & Jest mockup. 我正在尝试使用Jest&Jest模型为我的ES6应用程序编写测试用例。 But the mockup is not at all picked by the test suite. 但是这个模型根本没有被测试套件选中。 Can someone let me know the proper way to test 有人能让我知道正确的测试方法

request.js request.js

class Request{

  //
  // Set Header for All the requests
  //
  static get HEADERS() {
    return  {
              "Accept":  "application/json, text/plain", 
              "Content-Type": "application/json"
            };
    }

  //
  // GET Request
  //  
  static get(url){
    return fetch(url)
            .then(response => {
                if (!response.ok) {
                throw new Error(response.statusText);
              }
              return response.json();
          })
   .catch(err => {
      console.log(err);
    });
  }
  }

request.js //jest-mockup request.js // jest-mockup

import configureMockStore from 'redux-mock-store' // mock store 
import thunk from 'redux-thunk'

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)
const tasks = {
  "1": { "id": '1', "text": "Read description of programming challenge" },
  "2": { "id": "2", "text": "Implement awesome web app" },
  "3": { "id": "3", "text": "Polish project" }
};
import Request from '../scripts/lib/request';

describe('Request', () => {
    it('List all task fetch request', () => {
      console.log("11111");
      fetch.mockResponses(JSON.stringify(tasks));
      const expectedActions = [{ type: 'SET_TASKS', tasks}];
      const store = mockStore(tasks);
      return store.dispatch(store.get()) 
      .then(() => { // return of async actions
        expect(store.getActions()).toEqual(expectedActions)
      })
    }
}

request.spec.js //unit test request.spec.js //单元测试

import Request from '../../scripts/lib/request';

describe('request', () => {
    it('Should return all tasks', function() {
        var allTasks = Request.get("api/tasks");
        expect(allTasks).toEqual({
  "1": { "id": '1', "text": "Read description of programming challenge" },
  "2": { "id": "2", "text": "Implement awesome web app" },
  "3": { "id": "3", "text": "Polish project" }
});
    });
}); 

The problem is that fetch returns a promise. 问题是fetch返回一个promise。 Therefor you have to either return the promise from your test or use async/await , ( docs ): 因此,您必须从测试中返回promise或使用async/await ,( docs ):

import Request from '../../scripts/lib/request';
const result = {
  "1": {
    "id": '1',
    "text": "Read description of programming challenge"
  },
  "2": {
    "id": "2",
    "text": "Implement awesome web app"
  },
  "3": {
    "id": "3",
    "text": "Polish project"
  },
  "9": {
    "id": "9",
    "text": "Send solution to LogMeIn"
  }
});
describe('request', () = > {
  it('Should return all tasks', function () {
    var allTasks = Request.get("api/tasks");
    return get.then(() = >
      expect(allTasks).toEqual(result);
    )
  });
});
describe('request', () = > {
  it('Should return all tasks', async
    function () {
      var allTasks = await Request.get("api/tasks");
      expect(allTasks).toEqual(result);
    });
});
jest.dontMock('../scripts/lib/request');
import Request from '../scripts/lib/request';
const fs = require('fs')
Request.get = jest.genMockFn();
Request.get.mockImplementation(function(url) {
   let data = {
        "1": { "id": '1', "text": "Read description of programming challenge" },
          "2": { "id": "2", "text": "Implement awesome web app" },
          "3": { "id": "3", "text": "Polish project" },
        };
 return Promise.resolve(data);
});
export default Request;

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

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