Search code examples
hyperledger-fabrichyperledger-chaincode

How to mock two chaincodes while testing chaincode using fabric-mock-stub


I have been working on chaincode development and testing. I have successfully tested several single instances of chaincode but now I am stuck at a problem. One of my chaincode calls other chaincode. I am unable to mock two chaincodes in the test env.

So far I have went through docs of @theledger/fabric-mock-stub but to no avail. I tried trial and success by raising errors and reached a proper conclusion. " Error: Chaincode bank_contract/primarychannel could not be found. Please create this using mockPeerChaincode."

After working onto this error as follows:

let Chaincode = require("./transaction-contract.js");
let BankChaincode = require("../bank/bank-contract");
let fms = require("@theledger/fabric-mock-stub");
let chai = require("chai");
let expect = require("chai").expect;
let should = require("chai").should();
let globalTemp = "";
let globalTempAdmin = "";

let ChaincodeMockStub = fms.ChaincodeMockStub; 
const chaincode = new Chaincode();
const bankChaincode = new BankChaincode();
const mockStub = new ChaincodeMockStub("transaction_chaincode", 
 chaincode);
const bankMockStub = new ChaincodeMockStub("bank_contract", 
 bankChaincode);
mockStub.mockPeerChaincode("bank_contract", bankMockStub);

I am still getting the same error on executing the chaincode function.

My Questions:

  1. Am I doing it right? The way I make two mock stubs and then register one on another.
  2. How can I specify channel name as according to me, that's where my code is failing

Solution

  • You have to create and register your second chaincode with name <chaincode_name>/<channel_name>. In your case it should be

        const bankMockStub = new ChaincodeMockStub("bank_contract/primarychannel", bankChaincode);
        mockStub.mockPeerChaincode("bank_contract/primarychannel", bankMockStub);
    

    I don't know why but this is how ChaincodeMockStub.invokeChaincode works:

           if (channel != '') {
                chaincodeName = chaincodeName + '/' + channel;
            }
    

    More details here.