Chai - Setting a variable inside a request

issueId is undefined when it should be returning an Id. How can I set a variable inside a request in Chai? Thanks

suite('Test Test(s)', () => {
  let issueId = "";

  test('PUT request', done => {
   chai.request(server)
    .post('/api/issues/testProject')
    .set('content-type', 'application/json')
    .send({
      issue_title: "Issue Title",
      issue_text: "Issue Text",
      created_by: "Admin"
    })
    .end((err, res) => {
      issueId = res.body._id;     
    });

    console.log(issueId); // Returns undefined
    });
});

Hello!

You cannot use a declared variable outside of an asynchronous context. In this case, the .end(callback) is asynchronous, therefore the value will be set after you log it using console.log.

Take a look at this sample code:

HTML

<h2>Results</h2>
<div class="outpu"></div>

CSS

.output {
  padding: 1rem;
}

.output span {
  display: block;
  width: 100%;
  padding: 1rem .5rem;
}

.output span:nth-child(odd) {
  background: #dedede;
  color: black;
}

.output span:nth-child(even) {
  background: #999;
  color: white;
}

JavaScript

const result = document.querySelector('.output');

function write(str) {
  const span = document.createElement('span');
  span.innerText = str;
  result.append(span);
}

write("Starting script");

function asyncFn(callback) {
	// Simulate a function that takes time to complete but returns immediately
  const t = setTimeout(() => {
    callback('Finished');
    clearTimeout(t);
  }, 1000);
}

write("Declaring contextual variable");
let contextVar;

function asyncFnCaller() {
  asyncFn((response) => {
  	write(`Result of the callback: ${response}`);
    contextVar = response;
    write(`contextVar inside the callback: ${contextVar}`);
  })
}

write("Invoking the asyncFnCaller");
asyncFnCaller();

write(`Content of the context variable: ${contextVar}`)

In this code, the asyncFnCaller is like the .end function.

Try to understand how the example works and see if you can figure out why it doesn’t work :slight_smile:.

Something to increase your knowledge https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous:

1 Like

Thank you so much! Right now, I am very confused about Asynchronous Javascript. I’ll try to understand it as much as I can :smiley:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.