【问题标题】:node.js Mocha : how to reuse a variable defined in a local setup before() hook?node.js Mocha:如何重用在本地设置 before() 挂钩中定义的变量?
【发布时间】:2017-04-16 07:15:08
【问题描述】:

更新

在我的 ('resource' 测试中,我创建了一个新用户

/**
 * 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();
  });
});

我想在我的测试中重复使用用户 ID:

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);
    });
  });
   ...
});

但用户未定义..

我怎样才能改变它? 感谢反馈

【问题讨论】:

  • 将其移至上层范围,在之前运行并赋值,然后调用完成。
  • 感谢您的反馈,我在按照您的评论尝试后更新了我的问题。我可能又错了...它现在没有移到更高的范围吗?
  • 好的,谢谢我现在知道了.. let newUser = new User({}); before((done) => { newUser = new User({ let resource = { name: 'RS123', description: 'RS123Description', owner: newUser.id, private: true };

标签: node.js tdd mocha.js


【解决方案1】:

如果您在 before 块中使用 this 声明一个变量,您可以在该夹具的所有测试中重用它:

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

【讨论】:

  • 请注意,此答案不像您的问题示例那样使用箭头函数。 mocha 中不鼓励使用箭头函数,因为您的代码无法访问 mochas 上下文,因此 this.
猜你喜欢
  • 2022-06-20
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
相关资源
最近更新 更多