简体   繁体   中英

node.js Mocha : how to reuse a variable defined in a local setup before() hook?

UPDATED

In my ('resource' test , I create a new User

/**
 * root level hooks
 */
before((done) => {
  const newUser = new User({
    username: 'johndoe',
    password: 'jdpwd',
    email: 'johndoe@example.com',
    mobileNumber: 123456789
  });
  newUser.save((err) => {
    // console.log('error: ', err);
    done();
  });
});

I would like to reuse the user id in my test :

describe('## Resource APIs', () => {
const user = User.findOne({ username: 'johndoe' });
console.log('got user: ', user.id);
  let resource = {
    name: 'RS123',
    description: 'RS123Description',
    owner: user._id,   <= should be the id of the newUser
    private: true
  };
  describe('# POST /api/v1/resources', () => {
    it('should create a new resource', (done) => {
      request(app)
        .post('/api/v1/resources')
        .send(resource)
        .expect(httpStatus.OK)
        .then((res) => {
          expect(res.body.name).to.equal(resource.name);
          expect(res.body.description).to.equal(resource.description);
          resource = res.body;
          done();
        })
        .catch(done);
    });
  });
   ...
});

but user is undefined..

how can I change it ? thanks for feedback

if you declare a variable in the before block using this , you can reuse it in all tests of that fixture:

describe('create draft', function() {
  before(function() {
    this.user = ...
  });
  it('....', function(){
      this.user ....
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM