How I mock NetSuite modules in my SuiteScript unit tests
Created: February 24, 2025
When I work with SuiteScript clients on their unit testing practices, one of the primary struggles is how to handle dependencies on NetSuite modules within their tests.
Unit tests run outside of NetSuite, and SuiteScript modules like N/record
and
N/search
aren't actually defined in your project, so any references to those
modules within the code you're trying to test will fail.
One solution is to "mock" the NetSuite module in the unit test - which effectively creates a "fake" version of the NetSuite module.
Here's a real-world example of how I mocked the N/runtime
module when I was
testing code that depended on both the runtime.EnvType
enumeration and the
runtime.getCurrentUser()
method:
import runtimeLib from 'N/runtime'
jest.mock('N/runtime',
() => ({
EnvType: {
PRODUCTION: 'production',
SANDBOX: 'sandbox'
},
getCurrentUser: () => ({
id: 421
})
}),
{ virtual: true }
)
global.runtime = runtimeLib
Setting the virtual
flag is imperative; since the NetSuite modules aren't
actually defined in my project, they need to be mocked as virtual modules.
After that, I need to add the virtual mock to the global
closure for Jest, and
it must be named the same as the name my code-under-test uses for the module (
e.g. runtime
here). Hopefully, you're always referencing NetSuite modules with
the same variable name across all your modules, else this will get more painful.
Now, when I execute my unit test, any references to a global object named
runtime
contained within my code under test will use the object I've defined
here - instead of failing with a "runtime is not defined" or similar
ReferenceError
.
For more on Jest's virtual mocks, see the jest.mock() docs.
For a working project which includes virtual mocks (including the one presented here), see this repository
Happy testing.