javascript - Jest - simular portable-fetch
Tenho problemas para escrever testes para o portable-fetch. Descobri que quando estou usando a importação antiga "require" posso fazer mock facilmente, mas quando estou usando "import *" tudo quebra.
Código de exemplo para classe de teste:
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);
});
});
código de classe com duas amostras de 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;
saída para (1) Teste falhou:
TypeError: fetch is not a function
console.log fetch: { _isMockFunction: true,
getMockImplementation: [Function],
mock: { calls: [], instances: [] },
...
saída para (2) Teste aprovado:
console.log
fetch: function () {
const mockState = mocker._ensureMockState(f);
const mockConfig = mocker._ensureMockConfig(f);
...
Estou gerando API typescript-fetch usando https://editor.swagger.io/. O Swagger gera cliente com import(1). Como você pode ver, até mesmo o objeto mock parece diferente para import com require. Não consigo entender por que há tantas diferenças usando outro tipo de import. Amostra de código forked