2017-01-21 17 views
5

Я попытался с помощью следующего кода:Mock ответ на молнии с помощью выборки-насмешка

require('isomorphic-fetch'); 

const fetchMock = require('fetch-mock'), 
    fsp = require('fs-promise'), 
    unzip = require('unzip'), 
    rimraf = require('rimraf-then'), 
    path = require('path'); 

let zipLink = 'https://github.com/stevemao/left-pad/archive/master.zip', 
    out = 'left-pad-master'; 

// Careful: lib might be removed at any moment. 
fetchMock.get(zipLink, 
    fsp.createReadStream(path.join(__dirname, 'left-pad-master.zip'))); 

rimraf(out) 
    .then(() => fetch(zipLink)) 
    .then(response => { 
     return new Promise((resolve, reject) => { 
      // For example purpose, just parse zip file, and log each entry. 
      response.body.pipe(unzip.Parse()) 
       .on('entry', (entry) => console.log(entry.path)) 
       .on('close', resolve) 
       .on('error', reject); 
     }); 
    }) 
    .then(() => console.log('done')) 
    .catch(console.log); 

Но он бросает:

Error: invalid signature: 0x725f227b 
    at C:\dev\unzip-mock\node_modules\unzip\lib\parse.js:59:13 
    at runCallback (timers.js:628:20) 
    at tryOnImmediate (timers.js:601:5) 
    at processImmediate [as _immediateCallback] (timers.js:578:5) 

Если закомментировать fetchMock.get вызов, и работать с реальным fetch это работает хорошо.

код доступен на https://github.com/mlewand/unzip-mock-example

ответ

4

Передайте экземпляр Response в качестве второго параметра fetchMock.get() где тело объекта ответа является поток локального файла:

require('isomorphic-fetch'); 

const fetchMock = require('fetch-mock'), 
    fsp = require('fs-promise'), 
    unzip = require('unzip'), 
    rimraf = require('rimraf-then'), 
    path = require('path'); 

let zipLink = 'https://github.com/stevemao/left-pad/archive/master.zip', 
    out = 'left-pad-master'; 

// Careful: lib might be removed at any moment. 
var resp = new Response(
    fsp.createReadStream(path.join(__dirname, 'left-pad-master.zip')), 
    { headers: { "Content-Type" : "application/zip" } } 
); 
fetchMock.get(zipLink, resp); 

rimraf(out) 
    .then(() => fetch(zipLink)) 
    .then(response => { 
     return new Promise((resolve, reject) => { 
      // For example purpose, just parse zip file, and log each entry. 
      response.body.pipe(unzip.Parse()) 
       .on('entry', (entry) => console.log(entry.path)) 
       .on('close', resolve) 
       .on('error', reject); 
     }); 
    }) 
    .then(() => console.log('done')) 
    .catch(console.log); 
+0

Отлично, это то, что мне не хватает , Большое вам спасибо за ответ! –

 Смежные вопросы

  • Нет связанных вопросов^_^