gpt4 book ai didi

javascript - Hook 之前的 Mocha 在套件之前没有运行

转载 作者:搜寻专家 更新时间:2023-10-31 23:50:19 25 4
gpt4 key购买 nike

我是 Node 和 Mocha 的新手,我很难理解为什么 Mocha 在以下示例中跳过我的“之前” Hook 代码来创建 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 放在同一个测试 block 中,以便在处理之前运行它。例如:

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);
}));
};

关于javascript - Hook 之前的 Mocha 在套件之前没有运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53853370/

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