Search code examples
nearprotocol

How to change Context.sender in a NEAR Smart Contract unit test (web assembly)?


I have a function, addWord(word:string), which prohibits the same Context.sender from adding more than one consecutive word. I store the last signee in the contract. Forgive me if there are some syntax errors in the code below, I only added parts of my current code.

export class Contract {
 private lastSignedBy: string = '';
 private words: PersistentVector<string> = new PersistentVector<string>('w');

 @mutateState()
 addWord(word: string): number {
  // can't add more than one consecutive word
  if(this.lastSignedBy != Context.sender){
    this.words.push(word);
    this.lastSignedBy = Context.sender;
    return 1;
  }
  return 0; 
 }
}

Now, I want to test this function, but I don't know how to change the sender in the test. I think Maybe I need to mock the Context, but I'm not sure how to do that. The test framework is as-pect

Here is my current test.

let contract: Contract;
    
beforeEach(() => {
  contract = new Contract();
});
    
describe('Contract', () => {
  it('can add word if different sender than last time', () => {
    expect(contract.addWord('word one')).toStrictEqual(1);
    // TODO change Context.sender somehow. 
    expect(contract.addWord('second word')).toStrictEqual(1);
  });
}

Solution

  • You can use a reference to VMContext like this

    import { VMContext } from "near-sdk-as";
    ...
    
    it("provides access to most recent player", () => {
      VMContext.setSigner_account_id('player1')
    });
    
    

    https://github.com/Learn-NEAR/NCD.L1.sample--lottery/blob/2bd11bc1092004409e32b75736f78adee821f35b/src/lottery/__tests__/index.unit.spec.ts#L68