I am trying to test one of my contracts, but truffle complains that it is not defined. I can see that the test compiles to the build folder, and I have imported it the same way as other contracts, I am not sure what I am missing.

The contract:

contract OPCToken is AccessControl, StandardToken {

    constructor() {
        owner = msg.sender;

Then I have the deployment script

var OPCToken = artifacts.require("OPCToken");

module.exports = function(deployer) {

Then I have my test:

var OPCToken = artifacts.require("OPCToken");

contract('OPCToken', function(accounts) {

    it("any C level address can open the contract for applications", async () => {
        const OPCToken = await OPCToken.deployed(); // it throws here that OPCToken is not defined.
  • I wondered whether it is because the contract inherits from two other contracts, perhaps I need to wait for these to be deployed also? However I've tried importing and then awaiting both AccessControl and StandardToken, in various orders, and none of them seem to be defined (despite all of them definitely being deployed). Worth pointing out that I've tried to import from var OPCToken = artifacts.require("OPCToken"); and var OPCToken = artifacts.require("./OPCToken"); Aug 8 '18 at 8:10
  • What error do you get? I don't think it's caused by inheritance. When a contract A inherits from B, a deployed A IS a B. Inheriting from another contract is B adding that contract's funtionality to A.
    – Henk
    Aug 8 '18 at 8:12
  • @Henk you were right, it was not causing by inheritance but because I was overwriting the import statement! I've left an answer for other people who may encounter this problem too. Aug 8 '18 at 8:24
  • You're declaring the same variable (OPCToken) twice. What's the point in that? Aug 8 '18 at 8:43

Ah, I got it. It's a Javascript error.

It's because I am overwriting the OPCToken that I am importing, here:

const OPCToken = await OPCToken.deployed();

It works if I do this instead:

const opcToken = await OPCToken.deployed();

I am still a little confused as to why though - doesn't the right hand side evaluate first (at which point it's not been overwritten) - and the lefthand side assignment happen after. Is this different in the truffle test env?


The solution is to simply rename OPCToken as it clashes with the contract name.

There's a difference between left/right-hand side evaluation order and variable declaration logistics.

const myVar = 3;
const myVar = myVar * 14;

The code above will trigger a warning:

myVar was used before it was declared, which is illegal for const variables

Check it out on jsfiddle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.