Mocking Method Examples

The following code sample will mock the runtime.getCurrentScript() method with the mockReturnValue() Jest mock function. This mock function allows you to return an arbitrary value for this method. Note that this method returns a runtime.Script object, which we'll use as the mock return value. This object is represented as Script in the following example, because that is how it was defined. Note that you can name this object to your liking.

          import runtime from 'N/runtime'; // import runtime module
import Script from 'N/runtime/script'; // import script object from runtime module

describe('Mocking SuiteScript dependencies', () => {
   it('Should mock Suitescript method', () => {
      // given
      runtime.getCurrentScript.mockReturnValue(Script); //returns runtime.Script object 
 
      // then 
      expect(runtime.getCurrentScript).toHaveBeenCalled();
   });
}); 

        

The following code sample will mock the Script.getParameter(options) method with the mockImplementation() Jest mock function. This method returns any number, date, string, boolean, or null value depending on script logic. This example shows the number 15 as the value returned to represent an internal ID. It is important to note that you can set this value to any of the types mentioned in your test. Any arbitrary value will work.

          import runtime from 'N/runtime'; // import runtime module from runtime.js stub file
import Script from 'N/runtime/script'; // import script object from Script.js stub file

describe('Mocking SuiteScript dependencies', () => {
   it('Should mock Suitescript method', () => {
       // given
       runtime.getCurrentScript.mockReturnValue(Script); 
       Script.getParameter.mockImplementation(options => options.name === 'custscript_example_test' && 15); // returns 15
 
       // then 
       expect(runtime.getCurrentScript).toHaveBeenCalled();
       expect(Script.getParameter).toHaveBeenCalledWith({name: 'custscript_example_test'});
       expect(Script.getParameter).toHaveReturnedWith(15);
   });
}); 

        

Related Topics

General Notices