Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to return value in async testing via done? #1671

Closed
chenweiyj opened this issue Apr 25, 2015 · 4 comments
Closed

How to return value in async testing via done? #1671

chenweiyj opened this issue Apr 25, 2015 · 4 comments

Comments

@chenweiyj
Copy link

I am testing my apis by using mocha. Since calling to my apis needs authorization, I call the authorization api to get the access token in the beforeEach hook. I wrap the doFakeAuth function in the utils.js file and export it, which is denoted as follows.

exports.doFakeAuth = function (done) {
  var route = '/v1/auth/weibo';
  var body = {
    weibo_uid: 'test_weibo_uid_full_data',
    avatarurl: 'http://fake_weibo',
    birth_year: 1995,
    birth_month: 5,
    birth_day: 8,
    gender: 2,
    nickname: 'cw',
    signature: 'i will win'
  }

  request(url)
    .post(route)
    .send(body)
    .expect('Content-Type', /json/)
    .expect(200)
    .end(function (err, res) {
      if (err) throw err;
      //
      res.body.should.have.property('user');
      res.body.should.have.property('token');
      res.body.user.should.have.length(24);
      return res.body.token;
      done();
    });
}

However, I cannot get the res.body.token in the async call. I also tried

done(res.body.token);

But it said Error: done() invoked with non-Error: <token detail>.

So how can I get the token in the caller.

@boneskull
Copy link
Contributor

  return res.body.token;
  done();

The above is a basic misunderstanding of programming. Once you return from a function, any subsequent lines within the function are unreachable.

I'm not sure really what I'm looking at here. Is utils.js code under test, a fixture, or what? If you need to call some async function and get its return value:

describe('foo', function() {
  var response;
  beforeEach(function(done) {
    someAsyncCall(function(err, data) {
      response = data;
      done();
    });
  });
  it('should blah blah', function() {
    // use response here
  });
});

@schatekar
Copy link

@boneskull How would you do this if beforeEach is defined in a helper file to be used across multiple specs?

@boneskull
Copy link
Contributor

@schatekar do what..?

@schatekar
Copy link

If I have defined beforeEach in a separate file then how do I return value of response variable set inside beforeEach back to my specs?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants