我想设置一个请求,然后在多个测试中使用它。这是我最好的方法,但是不得不声明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()
并未返回其回调中返回的值。
是否有更好(更“优雅”)的方式来做到这一点?
答案 0 :(得分:1)
您可以简单地使用一个返回诺言的函数:
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
更具可读性,而INSERT INTO das_args (a,b,c,d) VALUES (1,2,3,4) ON DUPLICATE KEY UPDATE VALUES(1,2,3,4)
乍看之下并不可见。
答案 1 :(得分:0)
根据我以前的经验,我通常将响应存储在一个变量中,然后在每个测试中访问该变量。看来您的情况只关心响应,因此下面的解决方案可能适用。
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
})
})
})
在我看来,使变量可变是不奇怪的。
希望有帮助