Replies: 3 comments
-
You are correct, so Contract class adds these methods at construction time using abi provided.
Mocking provider can be the general approach if you cannot mock contracts. Just that you'd have to deal with ABI encoding and decoding, which should be fine if there are just a few methods that you want to mock. But if it's possible to use a different Contract class, you might be able to avoid that. class MyContract extends ethers.Conctract {
constructor() {
super(ethers.constants.AddressZero, []);
}
balanceOf() {} // you might be able to mock this method using jest
} |
Beta Was this translation helpful? Give feedback.
-
You were almost there. You have to mock the Contract constructor and return an object with the contract methods you want to mock.
Then you can work with Contract.balanceOf the same as with
Or if you are using
|
Beta Was this translation helpful? Give feedback.
-
Here is also solution which I have prepared with better control over mock function to help asserting on mock functions! |
Beta Was this translation helpful? Give feedback.
-
Hi there,
I'm encountering some difficulty writing tests for my node typescript application that uses Ethers and Jest.
I am using an Ethers contract that is of the type Uniswap NonFungiblePositionManager.
I would like to write unit tests that make use of the ethers contract. I have a class with private member called
nfpContract
and a method calledgetPositions
Let's say this is my code. I would like to write a unit test for getPositions. My first instinct is to mock "@ethersproject/contracts" and then overwrite the constructor to return a mock with the method getPositions. The problem I am having is that the Contract constructor returns an object instance that has no pre-set methods on it, so this doesn't seem to be working:
In this case, I can't do any tests on
PositionService.nfpContract.balanceOf
because it doesn't recognize it as a mocked method, because that method isn't known by the Contract class. Am I missing something here?This thread suggests bypassing the contract itself in the unit test and instead mocking the provider. As I write this, this seems to make sense because what I really care about is the proper method being called on the provider, not the exact implementation of the library that that actually formats the RPC call. Any confirmations or suggestions in this matter would be helpful.
P.S. How would I go about mocking
callStatic
on any of these methods then? Would that also just be easier if I mocked the provider?Beta Was this translation helpful? Give feedback.
All reactions