Hi all, I'm trying to solve this problem for mult...
# suitescript
s
Hi all, I'm trying to solve this problem for multiple days but can't figure it out. I'm trying to write unit tests for a (server side) user event script. sample code:
Copy code
define(['N/runtime'], function(runtimeModule){

    // this line will run on import and get executed before "{ beforeSubmit, }" is returned
	const SCRIPT_VAR = runtimeModule.getCurrentScript().getParameter({name: "custscript_script_var"});
    
    function beforeSubmit(context){
      //....
	}
    return { beforeSubmit, }
})
unit-test code:
Copy code
import runtimeModule from 'N/runtime';

// the test errors is at this line 
// script == { beforeSubmit: beforeSubmit }
import script from 'script.js' 

jest.mock('N/runtime');

beforeEach(() => {
	jest.clearAllMocks();
});

describe('some description', () => {
	it('some description', () => {

	});
});
when I run this test I get this error:
Copy code
TypeError: runtimeModule.getCurrentScript is not a function
note: • moving
runtimeModule
function in the
beforeSubmit
function is not a possible solution for me, as we have many scripts with similar formatting and I don't not what to modify scripts for the test to work • setting
jest.mock('script.js', {() => jest.fn(() => {})})
will make the test pass but
beforeSubmit
will be mocked as well. and I need the un-mocked version of
beforeSubmit
in order to test it. • setting
jest.mock('script.js', () => ({ beforeSubmit: jest.requireActual('script.js'), runtimeModule: () => jest.fn(() => {}), }));
is going to error, because calling
jest.requireActual('script.js')
is going to call
runtimeModule.getCurrentScript
function. If anyone would be able to help I would greatly appreciate it. Thank You!
e
You don't want to mock
script.js
(I'm not even sure what that is); you want to mock
N/runtime
. There are examples of mocking SuiteScript modules in the README that will probably give you a good starting point.
There is also this package that makes mocking the SuiteScript modules a little easier IMO, but maybe save that for later.
Here is one of my own examples which mocks
getCurrentUser
in the runtime module
s
Thank you eric for your reply! as you can see in the sample test script that i'm mocking the
N/runtime
module, but it still errors. it seems to me that
jest.mock
only mocks after import, but in my case
runtimeModule.getCurrentScript
is being called during the import therefore it errors (i might be wrong with my explanation but i believe it to be the reason of erroring). (ps. the
script.js
script is the user event script thats uploaded to NetSuite)
Thank You for sharing your examples, it really helped! I added this line to the test script and the test passes now.
global.runtimeModule = () => jest.fn(() => {})
Thank You!