[英]Mocha before hook not being run before suite
我是Node和Mocha的新手,我很難理解為什么Mocha會跳過我的'before'鈎子代碼來創建一個Json Web Token,如下例所示:
//index.js const createJWT = require('./lib/config/createJWT'); const expect = require('chai').expect; before(async() => { const jwt = await createJWT() { return new Promise( function(resolve, reject) { resolve(jwt); } ) } const person = createPerson(jwt); }); //this is where the jwt is created, making it useless for createPerson describe('My other tests', () => { it('Customer sign up', async() => { const signUpText = await customerSignUp(page, frame); expect(signUpText).to.equal("You have signed up") }); }); });
createJWT()方法如下:
//createJWT.js module.exports = async() => { const options = { method: 'POST', url: 'https://my-website.auth.io/oauth/token', headers: { 'content-type': 'application/json' }, body: '{"client_id":"dew76dw7e65d7w65d7wde"}' }; request(options, function (error, response, body) { try { console.log(body); jwt = body; return jwt = body; } catch (error) { } }); };
當我調試時,跳過設置代碼。 有什么明顯的東西我不見了嗎?
我很確定你需要將before hook放在同一個測試塊中,以便在處理之前運行它。 例如:
before(async() => {
const jwt = await createJWT();
});
describe('My other tests', () => {
it('Customer sign up', async() => {
const signUpText = await customerSignUp(page, frame);
expect(signUpText).to.equal("You have signed up")
});
});
要么 :
describe('My other tests', () => {
before(async() => {
const jwt = await createJWT();
});
it('Customer sign up', async() => {
const signUpText = await customerSignUp(page, frame);
expect(signUpText).to.equal("You have signed up")
});
});
此外,您的createJwt
方法不返回Promise,這會阻止await工作。 你需要做這樣的事情:
module.exports = async() => {
const options = {
method: 'POST',
url: 'https://my-website.auth.io/oauth/token',
headers: {
'content-type': 'application/json'
},
body: '{"client_id":"dew76dw7e65d7w65d7wde"}'
};
return new Promise((resolve, reject) => request(options, function (error, response, body) {
if(error) {
reject(error);
}
resolve(body);
}));
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.