gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:51:09 24 4
gpt4 key购买 nike

已更新

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

/**
* 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com