javascript - 如何使用 Jest 测试 ES6 fetch 方法

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

我正在尝试使用 Jest 和 Jest 模型为我的 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" }
});
    });
}); 

最佳答案

问题是 fetch 返回一个 promise 。因此,您必须从测试中返回 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);
    });
});

关于javascript - 如何使用 Jest 测试 ES6 fetch 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44034709/

相关文章:

javascript - 使用 Jest 的 rewire 来监视私有(private)函数中使用的 console.log

javascript - 如何在 JS 控制台中获取 console.timeEnd() 的输出?

javascript - 在默认 gulp 任务中使用询问器

javascript - 有没有办法通过 React JSX 释放 ES6 的全部威力?

javascript - Node 以编程方式设置导入模块不可用的进程环境变量

babeljs - babel@7 和 jest 配置

javascript - Chrome 不会调整 SVG 图像的大小

javascript - 如何将 JSON 文本数组转换为 JavaScript 数组?

javascript - 将 ES6 中的导入语句和导出语句中的所有文件分组

reactjs - 使用 Jest 和 Enzyme 调用函数