testingtypeerrorsolidity

Solidity: TypeError: Cannot read properties of undefined (reading 'JsonRpcProvider') in a simple HelloWorld contract by trying to test


I'm trying to test a simple HelloWorld.sol File:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract HelloWorld 
{
    function hello() public pure returns (string memory)
    {
        return "Hello, World";
    }
}

with a HelloWorld.ts testfile

import "@nomiclabs/hardhat-ethers" ;
import { ethers } from "hardhat";
import { expect } from "chai";


describe("hello world", function()
{
    it("should say hello world", async function () 
    {
        const HelloWorld = await ethers.getContractFactory("HelloWorld");
        const hello = await HelloWorld.deploy();

        expect(hello).to.equal("Hello, World");
       
    });
});

After calling: npx hardhat test

I got result with a error message:

hello world
    1) should say hello world


  0 passing (78ms)
  1 failing

  1) hello world
       should say hello world:
     TypeError: Cannot read properties of undefined (reading 'JsonRpcProvider')
      at Object.<anonymous> (node_modules\@nomiclabs\hardhat-ethers\src\internal\ethers-provider-wrapper.ts:4:61)
      at Module._compile (node:internal/modules/cjs/loader:1218:14)
      at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
      at Object.require.extensions.<computed> [as .js] (node_modules\ts-node\src\index.ts:1608:43)
      at Module.load (node:internal/modules/cjs/loader:1081:32)
      at Function.Module._load (node:internal/modules/cjs/loader:922:12)
      at Module.require (node:internal/modules/cjs/loader:1105:19)
      at require (node:internal/modules/cjs/helpers:103:18)
      at Object.<anonymous> (node_modules\@nomiclabs\hardhat-ethers\src\internal\provider-proxy.ts:7:1)
      at Module._compile (node:internal/modules/cjs/loader:1218:14)

I already did an internet research for answers/ fixing, but was not able to find an appropriate one..

So I don't know how to solve it and what am I supposed to do?

Thanks in advance!

please see above

Don't know why i get this error...


Solution

  • take a look at your contract instance, once you deploy the contract with

    const hello = await HelloWorld.deploy();
    

    You must call the hello() function to get the correct output. Update your code with

    describe("hello world", function()
    {
        it("should say hello world", async function () 
        {
            const HelloWorld = await ethers.getContractFactory("HelloWorld");
            const helloWorldContract = await HelloWorld.deploy();
            await helloWorldContract.deployed();
    
            const hello = await helloWorldContract.hello();
            expect(hello).to.be.equal("Hello, World");
           
        });
    });
    

    You will notice that I also added the code await helloWorldContract.deployed(); this will wait until the deployment transaction is already on chain.

    Good luck !