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

标签 node.js tdd mocha.js

已更新

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

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

但用户未定义..

我该如何更改它? 感谢您的反馈

最佳答案

如果您使用 this 在 before block 中声明变量,则可以在该装置的所有测试中重用它:

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

关于node.js Mocha : how to reuse a variable defined in a local setup before() hook?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43434749/

相关文章:

mocha.js - Mocha beforeEach 没有运行

jquery - 无法在 openshift 上的 Nodejs 和 mongodb 中进行 POST

node.js - 通过 ssh (Cygwin) 的 npm 命令发生错误

javascript - NodeJs 使用 ExpressJs : TypeError: string is not a function at Function. app.render

node.js - Gulp 可以用于将图像转换为下一代格式吗?

ruby-on-rails - 如何测试命名路由?

c# - 双败赛数据结构

unit-testing - TDD 测试数据重复

node.js - NodeJS 的 Github 操作 - 本地文件的 'Error: Cannot find module'

带有 'import' js 文件的 JavaScript 测试 (mocha)