Unit test cannot read portal library data

Enonic version: 7.10.3
OS: Ubuntu

I’m writing unit tests according to https://developer.enonic.com/docs/writing-unit-tests.

When JS function use for the unit test, if that function gets data from enonic portal library, it gives null point exception. It seems we cannot read enonic portal library data when a function is use in the unit test.

src/main/resources/lib/util.js

const importedLibs = {
    portal: require('/lib/xp/portal')
};

exports.getKey = function() {
    var key = importedLibs.portal.getSiteConfig().key;
    return key;
}

src/test/resources/lib/util-test.js

const importedLibs = {
    test: require('/lib/xp/testing'),
    util: require('/resources/lib/util')
};

exports.testGetKey= function () {
    var result = importedLibs.util.getKey();
    test.assertEquals('key_expected_val', result);
};

Can I know , is there any way to read portal library data in unit tests

Hi @cherysan19,

I do not know exactly how you write your test, but to be able to return siteConfig in the Unit test you should set a site for a PortalRequest.

Please, have a look at these links how to do that:

HI
@asi I want to run a unit test on to getKey() function. In that function key variable value is getting from site config.

When running the unit test it give null value to key value

Check if you can get the site itself. If not then it’s most likely a context issue. You should be inside correct context (Context Library - Enonic Developer Portal).

getSiteConfig() returns the site configuration for current application as JSON.

It means that in your test you should prepared all necessary data to make it workable. You can see how to do that in the links which I mentioned in my previous answer.

For example, suppose you have an application named myapplication, and the configuration for a site within this application looks like this:

'siteConfig': {
   'applicationKey': 'myapplication',
   'config': {
         'Field': 42
    }
 }

If you call getSiteConfig with request in scope this app, then it will return

{
     'Field': 42
}
1 Like