Critical Issue: TypeError - The property 'interface' cannot be deconstructed from 'require(...)' because it is not defined

I am puzzled by the error I encounter when running 'npm run test' in the terminal. The error seems to originate from the file called lottery.test.js. Despite double-checking the syntax and ensuring that I exported the modules correctly from the compile file, I still face an issue in the test file. For those curious, the name of the solidity file is Lottery.sol.

Lottery.test.js:

// Modules 
const assert = require('assert'); // used for ganache assertion
const ganache = require('ganache-cli'); // local ethereum testing network 
const Web3 = require('web3'); // Web3 is a constructor function (that's why it is capitalized)

 // creating an instance of Web3
 const provider = ganache.provider();
 const web3 = new Web3(provider);
 
const { interface, bytecode } = require('../compile'); // destructors - going up the directory tree 



let lottery; 
let accounts; 

beforeEach( async() => {
    accounts = await web3.eth.getAccounts();

    lottery = await new web3.eth.Contract(JSON.parse(interface))
    .deploy({ data: bytecode })
    .send({ from: accounts[0], gas: '1000000' });

});

describe('Lottery Contract', () => {

    // General Test - Contract has been deployed
    it('deploys a contract', () => { 
        assert.ok(lottery.options.address);
    });

    // Test One - Allows one account to enter
    it('allows one account to enter', async () => {
        await lottery.methods.enter().send({
            from: accounts[0],
            value: web3.utils.toWei('0.02', 'ether') // converts value from ether to wei since value is measured in wei
        });

        const players = await lottery.methods.getPlayers().call({from: accounts[0]});

        assert.equal(accounts[0], players[0]);
        assert.equal(1, players.length); 
    }); 

    // Test Two - Allows more than one account to enter
    it('allows multiple accounts to enter', async () => {

        await lottery.methods.enter().send({
            from: accounts[0],
            value: web3.utils.toWei('0.02', 'ether') // converts value from ether to wei since value is measured in wei
        });

        await lottery.methods.enter().send({
            from: accounts[1],
            value: web3.utils.toWei('0.02', 'ether') // converts value from ether to wei since value is measured in wei
        });

        await lottery.methods.enter().send({
            from: accounts[2],
            value: web3.utils.toWei('0.02', 'ether') // converts value from ether to wei since value is measured in wei
        });

        const players = await lottery.methods.getPlayers().call({from: accounts[0]});

        assert.equal(accounts[0], players[0]);
        assert.equal(accounts[1], players[1]);
        assert.equal(accounts[2], players[2]);

        assert.equal(1, players.length); 
    }); 

    // Test Three - Only accounts that send more than 1 Ether can enter
    // Done by sending an entry fee LESS than what is expected and anticipating the error 
    // Using a Try-Catch structure 
    it('requires a minimum amount of ether to enter', async () => {

        try {  // trying to trigger an error 
        await lottery.methods.enter().send({
            from: accounts[0],
            value: 0
        }); 
        assert(false); // forcing the function to generate an error
    }
        catch(err){ // triggered when an error occurs
            
         assert(err);

        }
    });

    // Test Four - Only the manager can pick the winner 
    // By allowing someone else BESIDES the manager choose the winner causing an error 
    it ('Only manager can call pickWinner', async () => {

        try {
            await lottery.methods.pickWinner().send({
                from: accounts[1] // someone else - not the manager
            });
            assert(false); 

        } catch(err){
            assert(err); 
        }

    });
 
    // Test Five - Resets the lottery when done 
    it('Sends money to the winner and resets the players array', async () => {
        // 1. Entering the lottery means the player sends an amount of Ether (2 Ether here)
        await lottery.methods.enter().send({
            from: accounts[0],
            value: web3.untils.toWei('2', 'ether')
        });

        // 2. Initial balance should be less by 2 Ether
        const initialBalance = await web3.eth.getBalance(accounts[0]); // amount of Ether in units of wei in an account

        // 3. After picking the winner, the amounts are reset
        await lottery.methods.pickWinner().send({from: accounts[0]});

        // 4. Final balance should be more by 2 Ether (normal before entering)
        const finalBalance = await web3.eth.getBalance(accounts[0]);

        // 5. Difference should be less than 2 Ether - it's not exactly 2 because we have to pay for gas 

        const difference = finalBalance - initialBalance; 

        assert(difference > web3.untils.toWei('1.8', 'ether'));

    });


});

compile.js:

// Modules 
const path = require('path'); // module used to help build a path from compile.js to inbox.sol - guaranteed to be compatible with OS used  
const fs = require('fs');
const solc = require('solc'); 

const lotteryPath = path.resolve(__dirname, 'contracts', 'Lottery.sol');
const source = fs.readFileSync(lotteryPath, 'utf8'); // to read the content of the inbox.sol file
module.exports = solc.compile(source, 1).contracts[':Lottery']; // compilation statement 

Answer №1

Since I can't reply to ngambinos's post, I wanted to share that this method worked for me in the current year of 2021. (shout out to) ngambino0192:

The issue may be related to the version of the solc compiler being used. Upgrading to a newer version could potentially resolve the problem.

Give these steps a try:

  1. Delete the node_modules directory by running: rm -rf node_modules
  2. Delete the package-lock.json file by running: rm -rf package-lock.json
  3. Update the import statement in the .sol file to: pragma solidity ^0.4.25
  4. Update the import statement in the .sol file to: pragma solidity ^0.4.25
  5. Update the dependency in the package.json file to: "solc": "^0.4.25"
  6. Install new dependencies by running: npm install

After completing these steps, you should be able to proceed with running your tests.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Iterating over an array of objects and executing asynchronous operations

I am currently working with NextJS and managing an array of assets (images) within my state. The task at hand is to post these images to the API. To accomplish this, I have a specific object that handles the posting process using the following syntax: let ...

Material UI autocomplete bug: a frustrating issue with suggestions

I'm currently developing a single-page application using React, and I have a shipment page where multiple products and their quantities need to be added. I've implemented some functions for this scenario, and while they are working correctly (sen ...

Error in Discord Bot: discord.js showing TypeError when trying to read the length of an undefined property

I'm currently working on developing a Discord bot and using CodeLyon's Permissions V2 video as a guide for reference. There seems to be an issue in my message.js file which contains the following code: require('dotenv').config(); //cre ...

Input ENTER triggered JSON path loading

Upon clicking "enter", I am looking to display the description corresponding to the title. To achieve this, I have defined a variable to store the path of the description: var descri = json.query.results.channel.item.map(function (item) { return item. ...

The combination of subtracted geometries creates unusual lighting effects

When working with three.js, I have been experimenting with the concept of cutting out a window from a box geometry, which represents a wall. I came across a helpful csg (constructive solid geometry) extension on this GitHub repository. After successfully ...

How can you fix the problem of a failed Npm package installation and revert back to the previous working version

Having issues with npm failing to install new versions and instead deleting old ones is quite frustrating. Is there a way to revert back to the previous version of the package that was working fine? This error message keeps popping up: gulp -bash: /usr/ ...

Access the value within an object that contains an array and compare it with a different array

array1 = [{id: 1, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92e6f7e1e6a3d2e6f7e1e6bcf1fdff">[email protected]</a>', group_ids: ["25"], username: 'test1'}, {id: ...

I encountered an issue while trying to run npm install - ERESOLVE was unable to resolve the

After transferring my project to a new computer from Github, I removed the node modules and ran npm install. However, I encountered the following error: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve ... npm ERR! See /Users/jacksaunders/.npm/er ...

"What is the best way to use jQuery to create a toggle effect where one button controls the state

I'm looking to improve the efficiency of my code, but I'm not sure where to start in terms of making it more concise and organized. Any suggestions on how to streamline this code and keep it neat would be greatly appreciated. $(document).ready(fu ...

Puppeteer will not navigate to chrome://version when running in headless mode

Currently, I am utilizing the puppeteer.connect method to navigate to chrome://version in order to extract the user-agent being used by Puppeteer. Everything works fine when headless mode is disabled, but an error occurs when attempting it with headless mo ...

Utilizing Ajax for validation on Telerik Kendo Grid with Change Event

I am working with a Telerik Kendo Grid that has a column listing medical diagnoses. The list is populated using a method in the controller. My task is to verify whether a newly added diagnosis is already present in the grid, and only allow adding diagnoses ...

Guide to including spinner in React JS with TypeScript

I need help with adding a spinner to a React component. The issue I'm facing is that the spinner does not disappear after fetching data from an API. Can someone please point out what I am doing wrong? Here is the code snippet: import React, { useSta ...

Tips for minimizing the use of if-else statements in JavaScript (specifically in Node.js)

Depending on a specific parameter, the function needs to choose from over 100 JSON files and send a query to another system. There will be numerous queries, possibly in the hundreds. Using if else and switch statements would not be practical for managing ...

How can I display the value stored in draft.js in a different component using React?

I'm new to using React and struggling to figure out how to display the value from another component in the edit file component. I've successfully created a message using draft.js rich text editor and can save it to the backend database. Now, I ne ...

Sorting through a collection by using a nested array

I've been working on optimizing my code to prevent making new http requests to my API every time I need to filter results. Currently, I have an array called pageContent that is populated with data from an API fetch when the page loads. Each object in ...

Creating a universal App Namespace using Require.js and Backbone

I'm new to working with Require.js and I've encountered a problem that I initially thought would be simple, but it's turning out to be quite challenging. My goal is to create a global namespace for my Backbone application and load it as a m ...

Error: Axios return value is undefined if user is not found by the function

Trying to retrieve error messages from Express server using Redux Toolkit has presented some challenges. When no user is found, an error message is sent with a status code. Postman works fine in getting the error response but encountering issues on the cli ...

Updating Information Within Firebase Directories

I am managing the organization of folders within Firebase Database and I want to modify the paths of certain data entries. For example: Current: Users/[IDs]/Economy/Items Desired: Economy/Users/[IDs]/Items Is there a way to achieve this? (I am using java ...

Trouble with executing two asynchronous AJAX calls simultaneously in ASP.NET using jQuery

When developing a web application in asp.net, I encountered an issue with using jQuery Ajax for some pages. The problem arose when making two asynchronous Ajax calls - instead of receiving the results one by one, they both appeared simultaneously after the ...

Is there a way for me to determine the quality of a video and learn how to adjust it?

(function(){ var url = "http://dash.edgesuite.net/envivio/Envivio-dash2/manifest.mpd"; var player = dashjs.MediaPlayer().create(); player.initialize(document.querySelector("#videoPlayer"), url, })(); var bitrates = player.getBitrateInfoListFor("vid ...