Search code examples
javascriptblockchainethereumsolidity

Error using a smart contract variable in test.js file


Trying to use a variable called postCount from my smart contract in my test file which is returning an error undefined

Smart contract looks like:

contract SocialNetwork {
string public name;
uint public postCount = 0;

Test file looks like:

describe ('posts', async ()=> {
        let result

        before(async ()=> {
            result = await socialNetwork.createPost('This is my first post', {
                from: author
            })
            postCount = await socialNetwork.postCount()
        })

On testing, error being returned is:

1) Contract: SocialNetwork
   posts
     "before all" hook:
 ReferenceError: postCount is not defined
  at _callee5$ (D:/projex/socialmedia-blockchain/test/SocialNetwork.js:33:20)
  at tryCatch (node_modules\regenerator-runtime\runtime.js:65:40)
  at Generator.invoke [as _invoke] (node_modules\regenerator-runtime\runtime.js:303:22)
  at Generator.prototype.(anonymous function) [as next] (node_modules\regenerator-runtime\runtime.js:117:21)
  at step (test\SocialNetwork.js:5:191)
  at D:\projex\socialmedia-blockchain\test\SocialNetwork.js:5:361
  at run (node_modules\core-js\modules\es6.promise.js:75:22)
  at D:\projex\socialmedia-blockchain\node_modules\core-js\modules\es6.promise.js:92:30
  at flush (node_modules\core-js\modules\_microtask.js:18:9)
  at process._tickCallback (internal/process/next_tick.js:172:11)

Solution

  • Your Contract code should work fine. The Problem is your js variable postCount is not defined.

    describe ('posts', async ()=> {
        let result;
        let postCount;
    
        before(async ()=> {
            result = await socialNetwork.createPost('This is my first post', {
                from: author
            })
            postCount = await socialNetwork.postCount()
        })