有没有更好的方法在 Mocha 'before' 调用中定义变量?

Is there a better way to define a variable in a Mocha 'before' call?

我想设置一次请求,然后在多个测试中使用它。这是我能想到的最好的方法,但是必须声明 req 可变以便它在外部范围内可用似乎很奇怪。

describe('GET /password', () => {
  let req
  before(() => {
    req = chai.request(app).get('/password')
    return req
  })

  it('should get the password page', () => {
    return req.then(res => res.should.have.status(200))
  })

  describe('The password page', () => {
    it('should render HTML', () => {
      return req.then(res => res.should.be.html)
    })
  })
})

我希望我能做类似的事情

const req = before(() => {
  return chai.request(app).get('password')
})

...但似乎 before() 没有 return 在其回调中 return 编辑的值。

是否有更好的(更多 "elegant")方法来做到这一点?

根据我以前的经验,我通常将响应存储在一个变量中,然后在每次测试中访问该变量。似乎您的案例只关心响应,因此下面的解决方案可能适合。

describe('GET /password', () => {
  let response; // create a variable

  before(() => {
    return chai.request(app).get('/password') // add `return` here for promise
      .then(res => {
        response = res; // store response from api to the variable
      })    
  })

  it('should get the password page', () => {
    response.should.have.status(200);
  })

  describe('The password page', () => {
    it('should render HTML', () => {
      response.should.be.html
    })
  })
})

在我看来,将变量设为可变并不奇怪。

希望对您有所帮助

您可以简单地使用一个返回承诺的函数:

describe('GET /password', () => {

   function getPassword () {
      return chai.request(app).get('/password')
   }

   it('should get the password page', () => {
      return getPassword()
         .then(res => res.should.have.status(200))
         .catch(err => err.should.not.exist)
   })

   describe('The password page', () => {
      it('should render HTML', () => {
         return getPassword()
            .then(res => res.should.be.html)
            .catch(err => err.should.not.exist)
      })
   })

})

我发现使用函数也比使用 before 更具可读性,后者乍一看是不可见的。