如何使用Jest测试ES6 fetch方法

时间:2017-05-17 21:02:00

标签: javascript ecmascript-6 jestjs babel-jest jest-fetch-mock

我正在尝试使用Jest& amp为我的ES6应用编写测试用例开玩笑的模型。但是这个模型根本没有被测试套件选中。有人可以告诉我正确的测试方法吗

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

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 //单元测试

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" }
});
    });
}); 

2 个答案:

答案 0 :(得分:0)

问题是fetch会返回一个承诺。因此,您必须从测试中返回承诺或使用async/await,(FxCop 1.0):

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);
    });
});

答案 1 :(得分:0)

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;