[英]node.js Mocha : how to reuse a variable defined in a local setup before() hook?
更新
在(“資源”測試中,我創建了一個新用戶
/**
* 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塊中聲明變量,則可以在該燈具的所有測試中重用它:
describe('create draft', function() {
before(function() {
this.user = ...
});
it('....', function(){
this.user ....
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.