lundi 19 mars 2018

Jest - mock portable-fetch

I have problems with writing tests for portable-fetch. I found out that when I am using old "require" import I can mock it easily, but when i am using "import *" everything break down.

Sample code for test class:

const fetch = require('jest-fetch-mock');

jest.setMock('portable-fetch', fetch);
const factory = require('./current-weather');

describe('current-weather', () => {
  const config = { appid: 'appid' };
  const currentWeather = factory(config);

  test('currentWeather()', async () => {
    const weather = { temperature: '25.17 °C' };
    fetch.mockResponse(JSON.stringify(weather));

    const current = await currentWeather({ city: 'London' });

    expect(current).toEqual(weather);
  });
});

class code with two samples of imports require/import *

import * as fetch from "portable-fetch";//(1) not working
const fetch = require('portable-fetch');//(2) working

const factory = ({ appid }) => (
  async ({ city }) => {
    const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${appid}&units=metric`;
    console.log("fetch:", fetch)
    const currentWeather = await fetch(url)
      .then(response => (response.json)())
      .then(data => (data));
    return currentWeather;
  }
);

module.exports = factory;

output for (1) Test failed:

TypeError: fetch is not a function

console.log fetch: { _isMockFunction: true,
  getMockImplementation: [Function],
  mock: { calls: [], instances: [] },
  ...

output for (2) Test passed:

console.log
   fetch: function () {
   const mockState = mocker._ensureMockState(f);
   const mockConfig = mocker._ensureMockConfig(f);
   ...

I'm generating typescript-fetch api using https://editor.swagger.io/ Swagger generates client with import(1). As you can see even mock object looks different for import with require. I cannot understand why so many diffrences by using other import type. forked sample of code

Aucun commentaire:

Enregistrer un commentaire