[英]Mock a zip response using fetch-mock
I've tried with following code: 我试过以下代码:
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 );
But it throws: 但它抛出:
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)
If you comment out fetchMock.get
call, and work with a real fetch
it works well. 如果你注释掉
fetchMock.get
调用,并使用真正的fetch
它运行良好。
Code is available at https://github.com/mlewand/unzip-mock-example 代码可在https://github.com/mlewand/unzip-mock-example获得
Pass an instance of Response
as a second parameter to fetchMock.get()
where the body of response object is a stream of local file: 将
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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.