Javascript 如何使用Jest正确模拟文件读取器?

Javascript 如何使用Jest正确模拟文件读取器?,javascript,node.js,unit-testing,jestjs,mocking,Javascript,Node.js,Unit Testing,Jestjs,Mocking,我试图模拟一个文件读取器,我有一个接受回调的函数,但是在测试过程中,调用回调的行没有被覆盖。如何解决这个问题 功能: const testFunction = (uint8arr, callback) => { const bb = new Blob([uint8arr]); const f = new FileReader(); f.onload = function (e) { callback(e.target.result); }; f.readAsT

我试图模拟一个文件读取器,我有一个接受回调的函数,但是在测试过程中,调用回调的行没有被覆盖。如何解决这个问题

功能:

const testFunction = (uint8arr, callback) => {
  const bb = new Blob([uint8arr]);
  const f = new FileReader();
  f.onload = function (e) {
    callback(e.target.result);
  };

  f.readAsText(bb);
};

module.exports = { testFunction };
测试:


codesandbox:

您可以使用
对象的getter和setter.defineProperty()
方法拦截
onload
函数的赋值操作,因此您可以像往常一样获取
onload
函数来测试它

例如

index.js

const testFunction=(uint8arr,回调)=>{
const bb=新Blob([uint8arr]);
const f=新文件读取器();
f、 onload=函数(e){
回调(如target.result);
};
f、 readAsText(bb);
};
module.exports={testFunction};
index.test.js

const{testFunction}=require('./index');
描述('testFunction',()=>{
它('应该用blob值调用mockCallback和readAsText',()=>{
const mockCallback=jest.fn();
常量文件读取器={
readAsText:jest.fn(),
};
让onloadRef;
Object.defineProperty(文件读取器,“onload”{
得到(){
返回此文件。_onload;
},
设置(空载){
onloadRef=onload;
这个。_onload=onload;
},
});
spyOn(窗口,'FileReader').mock实现(()=>FileReader);
const uintArray=新Uint8Array();
testFunction(uintArray、mockCallback);
//空载试验
const event={target:{result:'teresa teng'}};
onloadRef(事件);
expect(mockCallback)。与('teresa teng')一起调用;
期望(fileReader.readAsText).toBeCalledWith(新Blob([uintArray]);
});
});
单元测试结果:

 PASS  examples/66964346/index.test.js (7.479 s)
  testFunction
    ✓ should be called mockCallback and readAsText with the blob value (4 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.575 s, estimated 9 s
 PASS  examples/66964346/index.test.js (7.479 s)
  testFunction
    ✓ should be called mockCallback and readAsText with the blob value (4 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.575 s, estimated 9 s