Q:

Postman scripting: cannot save environment variable via test script

I have a couple of requests as part of my collection and wanted to set an environment variable with a value from the JSON response output.
This variable is not defined in the Manage Environments section. 
Is it mandatory that I would have to first declare the environment variable under Manage Environments section? 
If I do declare it in the Manage Environments section, then it is working^
const jsonData = pm.response.json();
pm.environment.set('sessionId', jsonData.sessionId);

My other question is I'm at loss on why this is passing? 
I have the following code snippet in one of my requests:
{
    "sessionid": "15c3f72e-788f-423f-b1cc-5dca503ae859",
    "expires": "2019-02-17T20:57:20.24234222-08:00",
    "cookievalue": "MySession"
}

pm.test("Check if session id is returned"), function() {
    pm.expect(pm.response.text()).to.include("sessionid2");
}

I'm surprised by why this is working? 
It should fail since I don't have sessionid2 in the JSON response.
I tried all other ways including pm.response.json() and nothing works. 
Btw, how do I test to see if the key exists in the JSON response and not necessarily to check the value since the session id value may change each time?
Other than the docs, can somebody point me to a good resource to learn more about Postman scripting?

A:

The first question regarding saving an environment variable, you would need to create an environment file first, in order for it to know where to save the variable. You could use the pm.globals.set() function instead if you didn't want to create a file first. 
For the second question, it looks like your test syntax is wrong as you've closed off the test by adding the extra ) after the test name. 
Using something like this instead should work:
pm.test("Check if session id is returned", function() {
    pm.expect(pm.response.json()).to.include.key("sessionid");
})

