[英]Jest Mock Default Constructor
The test:考试:
import Web3 from 'web3';
jest.mock('web3', ()=>{
return jest.fn().mockImplementation(()=>'Hello, world!')
});
describe('app', ()=>{
test('mock web3', ()=>{
console.log('web3:', Web3);
let web3 = new Web3(window.ethereum);
console.log("new web3:", web3);
});
});
package.json
: package.json
:
{
"name": "test",
"dependencies": {
"react-scripts": "5.0.1",
"web3": "^1.7.5"
},
"devDependencies":{
},
"scripts": {
"test": "react-scripts test"
}
}
Invoke with npm i && npm test;
调用npm i && npm test;
. . The first console.log
shows that I have mocked the module.第一个console.log
显示我已经模拟了该模块。 The second console.log
shows that something went wrong.第二个console.log
显示出了点问题。 The output of the second log statement is第二条日志语句的output为
new web3: mockConstructor {}新的 web3:模拟构造器 {}
but I expect something like但我希望像
new web3: "Hello, world!"新的 web3:“你好,世界!”
I've tried many permutations including moving the import below jest.mock
and changing the import to const Web3 = require('web3');
我尝试了许多排列,包括将导入jest.mock
下面并将导入更改为const Web3 = require('web3');
. . If I remove the require
or import
, the test fails with "ReferenceError: Web3 is not defined" as expected.如果我删除require
或import
,测试将失败,并按预期显示“ReferenceError: Web3 is not defined”。
I've reviewed other questions including Jest: mock constructor function , Jest mock a constructor , and Mock a dependency's constructor Jest , which suggest that this method should work.我已经查看了其他问题,包括Jest: mock constructor function 、 Jest mock a constructor和Mock a dependency's constructor Jest ,这表明这种方法应该有效。 One salient difference is that I'm mocking a default import's constructor rather than a named import.一个显着的区别是我 mocking 是默认导入的构造函数,而不是命名导入。
How do I mock the Web3 constructor to return a mocked object?如何模拟 Web3 构造函数以返回模拟的 object?
For some reason, you can't use a jest.fn
like that.出于某种原因,您不能像这样使用jest.fn
It seems that you could, and lots of documentation suggests you can, so it's probably a bug.看起来你可以,并且很多文档表明你可以,所以这可能是一个错误。 As a workaround, use a regular function:作为解决方法,请使用常规 function:
jest.mock('web3', ()=>{
return function notJestFn() {return 'Hello, world!';}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.