Testing Conditional Statements
Be mindful of testing conditional statements as well. Conditional statements are automatically evaluated with Jest, so be sure to write tests that verify the logic.
The following example writes a test to verify that a client script with the validateLine(scriptContext) entry point function is being called with the correct parameters and value types. The script checks the scriptContext.sublistId value in the conditional statement. With this information, we can structure the unit test by setting this parameter value to pass or fail the condition.
exampleScript.js:
define(['N/record', 'N/runtime', 'N/log'], (record, runtime, log) => {
function validateLine(scriptContext) {
const recSalesOrder = scriptContext.currentRecord;
if (scriptContext.sublistId === 'item') {
const casePerPallet = recSalesOrder.getCurrentSublistValue({
sublistId: 'item',
fieldId: 'custcol_cases_per_pallet'
});
const quantity = recSalesOrder.getCurrentSublistValue({
sublistId: 'item',
fieldId: 'quantity'
});
}
}
exampleScript.test.js
The condition will fail in the example test file below because the sublistId is incorrect. Therefore we can expect the CurrentRecord.getSublistValue(options) method to not be called.
describe('Testing conditional statements', () => {
it('Should test validateLine function parameters', () => {
// given
scriptContext.currentRecord = CurrentRecord; // CurrentRecordObj
scriptContext.sublistId = 'name'; // condition fails
// when
script.validateLine(scriptContext);
// then
expect(CurrentRecord.getCurrentSublistValue).not.toHaveBeenCalled(); // function should not be called
});
});
The condition will pass in the example test file below because the sublistId is correct. Therefore we can expect the methods to be called twice.
describe('Testing conditional statements', () => {
it('Should test validateLine function parameters', () => {
// given
scriptContext.currentRecord = CurrentRecord; // CurrentRecordObj
scriptContext.sublistId = 'item'; // condition passes
// when
script.validateLine(scriptContext);
// then
expect(CurrentRecord.getCurrentSublistValue).toHaveBeenCalledTimes(2); // function will be called
});