Introduction to Unit Testing

Paultier’s solution worked for me.

1 Like

thanks man @slavenR this was giving me a head pain from long time…It worked perfectly fine

2 Likes

I got the exact same problem. When I tryed your solution truffle got uninstalled! I cant figure it out.

Never mind I figured it out. Truffle was supposed to get uninstalled! Then I installed it again. However it still wouldent work. However I got @Glenn_CostaRica’s solotion to work.

2 Likes

Hey @gabba!
I’m having trouble geting the test to work. I was wondering if you could help.
Here is the errer.

Here is the hellpworldtest.js code:

const Helloworld = artifacts.require("Helloworld");

contract("Helloworld", async function(){
  it("should initialze correctly", async function(){
    let instance = await Helloworld.deployed();
    let message = await instance.getMessage();
    assert(message === "Hello Again!");
  });
});

Hi @JRB
Hum i 'm not really sure why it’s failing , can you try to add a message to the assert function.

    let message = await instance.getMessage();
   console.log(message);
    assert(message === "Hello Again!", "test hello world");
2 Likes

I tried @Glenn_CostaRica solution, but I am running into some problems. For the last step, I get this:

  • Fetching solc version list from solc-bin. Attempt #1
    npm WARN saveError ENOENT: no such file or directory, open ‘C:\Users\15103\package.json’
    npm WARN enoent ENOENT: no such file or directory, open ‘C:\Users\15103\package.json’
    npm WARN 15103 No description
    npm WARN 15103 No repository field.
    npm WARN 15103 No README data
    npm WARN 15103 No license field.
  • [email protected]
    updated 1 package and audited 36 packages in 7.245s
    found 4 low severity vulnerabilities
    run npm audit fix to fix them, or npm audit for details

Honestly, I am clueless on ways I can fix this. Does anyone know ways to fix this? I tried

npm audit fix
npm audit

These do not solve my problem. I get these errors:

npm ERR! code EAUDITNOPJSON
npm ERR! audit No package.json found: Cannot audit a project without a package.json
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\15103\AppData\Roaming\npm-cache_logs\2020-06-01T01_31_33_672Z-debug.log
PS C:\Users\15103\Documents\ethereum-course-advanced\Helloworld>

Please let me know if you have any ways to resolve my issue, thank you!

Hi @chaneltiana

This is the error

no such file or directory, open ‘C:\Users\15103\package.json’

If you install truffle like this

Install Truffle again: $ npm install truffle

It will install it in your local repository, it’s better to install truffle globally

npm install -g truffle

I m seeing that you are trying to install it in your user directory

C:\Users\15103\

I think it’s better to create a folder and to do everything inside this folder

you can create it in the desktop for example

cd .\Desktop\
mkdir test
cd test

Then initialize your project

npm init

It will create the package.json file, so now if you want to install truffle locally you ll be able to

npm install truffle

:warning: Don’t install it twice if it’s install globally no need to install it locally

1 Like

Thank you @gabba! I was able to get past my last error, but I now get this error:

Contract: Helloworld
1) should initialize correctly
No events were emitted
0 passing (441ms)
1 failing

  1. Contract: Helloworld
    should initialize correctly:
    AssertionError: Unspecified AssertionError
    at Context. (test\helloworldtest.js:7:5)
    at process._tickCallback (internal/process/next_tick.js:68:7)

Do you know any solutions to do this?

cool @chaneltiana can you share the content of your test ?

helloworldtest.js

Your test is failing to initialize, are you calling the right contract in artifacts ?

1 Like

@gabba here is the code for my hellowworldtest.js:

const Helloworld = artifacts.require(“Helloworld”);
contract(“Helloworld”, async function(){
it(“should initialize correctly”, async function(){
let instance = await Helloworld.deployed();
let message = await instance.getMessage();
assert(message === “Hello Again!”);
});
});

@chaneltiana Ok your assert is failing can you display the instance in a console log ?

const Helloworld = artifacts.require(“Helloworld”);
contract(“Helloworld”, async function(){
it(“should initialize correctly”, async function(){
let instance = await Helloworld.deployed();
console.log("this is this instance");
console.log(instance);
let message = await instance.getMessage();
assert(message === “Hello Again!”);
});
});

Also try

truffle compile 
truffle migrate --reset
truffle test
1 Like

@gabba I tried the console log but I get this:

const Helloworld = artifacts.require(“Helloworld”);
^

SyntaxError: Invalid or unexpected token
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions…js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at C:\Users\15103\AppData\Roaming\npm\node_modules\truffle\node_modules\mocha\lib\mocha.js:250:27
at Array.forEach ()
at Mocha.loadFiles (C:\Users\15103\AppData\Roaming\npm\node_modules\truffle\node_modules\mocha\lib\mocha.js:247:14)
at Mocha.run (C:\Users\15103\AppData\Roaming\npm\node_modules\truffle\node_modules\mocha\lib\mocha.js:576:10)
at resolve (C:\Users\15103\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\test.js:138:1)
at new Promise ()
at Object.run (C:\Users\15103\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\test.js:137:1)
at process._tickCallback (internal/process/next_tick.js:68:7)
truffle(ganache)> test
Using network ‘ganache’.

My code from my previous message is the closest I have came to what I should be getting in the video

Why this time the output is not the same ?
Did you try to run the command i sent you

truffle compile 
truffle migrate --reset
truffle test

I can see that you are in the console, you should be in the console with the command i sent you.
Also type the double quote manually because sometime when they are copye past it the compiler doesn’t recognize it

1 Like

@gabba this is what I get after I do the “truffle test” command. This is with the code you sent as well. Not too sure what is wrong

@chaneltiana You did nothing wrong ^^ when you are testing truffle outside of the console you need to use a local node to validate the transaction (for example ganache) in the truffle-config.js file you can set your network name, id and port.

Now that you migration is successful we know that this is not the issue so to make it simple try again using

truffle console
test

Yes but as i told you don’t copy and past the code because the double quote -> " when it’s copy past cause issue in some terminal. So Copy past the code if you want to but replace manually the double quote.

1 Like

@gabba I fixed the problem when I copy and paste. I also did the two commands but now I get this:

detail







Ok @chaneltiana
We are making progress , so your instance is defined, we can see the getMessage function.
Can you try to console log the message now ?

const Helloworld = artifacts.require(“Helloworld”);
contract(“Helloworld”, async function(){
it(“should initialize correctly”, async function(){
let instance = await Helloworld.deployed();
let message = await instance.getMessage();
console.log("this is the message");
console.log(message);
assert(message === “Hello Again!”, "Error with my message");
});
});

Edit: add an error message in the assert

1 Like

Sorry for the delay, I tryed what you said however neerly the same errer ocured:


I am putting up the code of all files just in case there is an errer there and it somehow connects to this. However I am not putting up the json files because reily see why the problem would be connected to them.

Helloworld.sol

pragma solidity 0.5.12;

contract Helloworld {

  string message = "Hello World!";

  function getMessage() public view returns(string memory) {
    return message;
  }

  function setMessage(string memory newMessage) public payable {
    message = newMessage;
  }

}

Migrations.sol

pragma solidity >=0.4.21 <0.7.0;

contract Migrations {
  address public owner;
  uint public last_completed_migration;

  constructor() public {
    owner = msg.sender;
  }

  modifier restricted() {
    if (msg.sender == owner) _;
  }

  function setCompleted(uint completed) public restricted {
    last_completed_migration = completed;
  }
}

1_initial_migration.js

const Migrations = artifacts.require("Migrations");

module.exports = function(deployer) {
  deployer.deploy(Migrations);
};

2_Helloworld_deploy.js

const Helloworld = artifacts.require("Helloworld");

module.exports = function(deployer, network, accounts) {
  deployer.deploy(Helloworld).then(function(instance){
    instance.setMessage("Hello Again!!!", {value: 1000000, from: accounts[0]}).then(function(){
        console.log("Success!");
    }).catch(function(err){
        console.log("error: " + err);
    });
  }).catch(function(err){
      console.log("Deploy failed " + err);
  });
};

helloworldtest.js

const Helloworld = artifacts.require("Helloworld");

contract("Helloworld", async function(){
  it("should initialze correctly", async function(){
    let instance = await Helloworld.deployed();
    let message = await instance.getMessage();
    console.log(message);
    assert(message === "Hello Again!", "test hello world");
  });
});

truffle-config.js

/**
 * Use this file to configure your truffle project. It's seeded with some
 * common settings for different networks and features like migrations,
 * compilation and testing. Uncomment the ones you need or modify
 * them to suit your project as necessary.
 *
 * More information about configuration can be found at:
 *
 * truffleframework.com/docs/advanced/configuration
 *
 * To deploy via Infura you'll need a wallet provider (like @truffle/hdwallet-provider)
 * to sign your transactions before they're sent to a remote public node. Infura accounts
 * are available for free at: infura.io/register.
 *
 * You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
 * public/private key pairs. If you're publishing your code to GitHub make sure you load this
 * phrase from a file you've .gitignored so it doesn't accidentally become public.
 *
 */

// const HDWalletProvider = require('@truffle/hdwallet-provider');
// const infuraKey = "fj4jll3k.....";
//
// const fs = require('fs');
// const mnemonic = fs.readFileSync(".secret").toString().trim();

module.exports = {
  /**
   * Networks define how you connect to your ethereum client and let you set the
   * defaults web3 uses to send transactions. If you don't specify one truffle
   * will spin up a development blockchain for you on port 9545 when you
   * run `develop` or `test`. You can ask a truffle command to use a specific
   * network from the command line, e.g
   *
   * $ truffle test --network <network-name>
   */

  networks: {
    // Useful for testing. The `development` name is special - truffle uses it by default
    // if it's defined here and no other network is specified at the command line.
    // You should run a client (like ganache-cli, geth or parity) in a separate terminal
    // tab if you use this network and you must also set the `host`, `port` and `network_id`
    // options below to some value.
    //
    // development: {
    //  host: "127.0.0.1",     // Localhost (default: none)
    //  port: 8545,            // Standard Ethereum port (default: none)
    //  network_id: "*",       // Any network (default: none)
    // },

    // Another network with more advanced options...
    // advanced: {
      // port: 8777,             // Custom port
      // network_id: 1342,       // Custom network
      // gas: 8500000,           // Gas sent with each transaction (default: ~6700000)
      // gasPrice: 20000000000,  // 20 gwei (in wei) (default: 100 gwei)
      // from: <address>,        // Account to send txs from (default: accounts[0])
      // websockets: true        // Enable EventEmitter interface for web3 (default: false)
    // },

    // Useful for deploying to a public network.
    // NB: It's important to wrap the provider as a function.
    // ropsten: {
      // provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`),
      // network_id: 3,       // Ropsten's id
      // gas: 5500000,        // Ropsten has a lower block limit than mainnet
      // confirmations: 2,    // # of confs to wait between deployments. (default: 0)
      // timeoutBlocks: 200,  // # of blocks before a deployment times out  (minimum/default: 50)
      // skipDryRun: true     // Skip dry run before migrations? (default: false for public nets )
    // },

    // Useful for private networks
    // private: {
      // provider: () => new HDWalletProvider(mnemonic, `https://network.io`),
      // network_id: 2111,   // This network is yours, in the cloud.
      // production: true    // Treats this network as if it was a public net. (default: false)
    // }
  },

  // Set default mocha options here, use special reporters etc.
  mocha: {
    // timeout: 100000
  },

  // Configure your compilers
  compilers: {
    solc: {
       version: "0.5.12",    // Fetch exact version from solc-bin (default: truffle's version)
      // docker: true,        // Use "0.5.1" you've installed locally with docker (default: false)
      // settings: {          // See the solidity docs for advice about optimization and evmVersion
      //  optimizer: {
      //    enabled: false,
      //    runs: 200
      //  },
      //  evmVersion: "byzantium"
      // }
    }
  }
}

Hello @JRB

Your test is failing because your message is
“Hello Again!!!”
and you are testing if it’s equal to
“Hello Again!”
So it’s normal ^^
“Hello Again!!!” is not equal to “Hello Again!”

2 Likes

@gabba I just tried this solution, but I still get the same outcome: