![](/img/trans.png)
[英]Mocha - pass variable to `beforeEach` and `afterEach` from `it`
[英]Pass variable from before() to it() in mocha
自动化非常新,我试图将令牌值从block()
之前传递给it()
并且我得到未定义。
能够成功生成并保存在token
中
const { spec } = require('pactum');
const request = require('request');
const userConfig = require('../config/credential.json')
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
let token = "";
let authToken = "";
describe('POST /jobs', function () {
before(function () {
var option = {
'method': 'POST',
'url': 'https://login.microsoftonline.com/<tenant_id>/oauth2/v2.0/token',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'client_id': `${userConfig.client_id}`,
'grant_type': 'password',
'Password': `${userConfig.Password}`,
'UserName': `${userConfig.UserName}`,
'scope': `${userConfig.scope}`,
'client_secret': `${userConfig.client_secret}`
}
};
request(option, function (error, response) {
if (error) throw new Error(error)
const modifyResponse = JSON.parse(response.body)
token = modifyResponse["access_token"]
})
})
it('Create Job should return 201 status code', async () => {
authToken = this.token
console.log('------------>', authToken)
await spec()
.post('https://localhost:3000/jobs')
.withHeaders('Authorization', `Bearer ${authToken}`)
.withHeaders('X-Client-Id', 'AzureDataLoaderUI')
.withHeaders('X-Message-Created-Ts', '2022-JUN-07 04:06')
.withHeaders('X-Message-Id', '4e8fb14c-c71f-46f8-b41a-561d393037ce')
.withHeaders('X-Transaction-Created-Ts', '2022-JUN-07 04:06')
.withHeaders('X-Transaction-Id', 'f11c97dc-a6eb-4ff7-aff6-de47c4686941')
.withHeaders('X-User-Id', 'AutoTestUser')
.withHeaders('Ocp-Apim-Subscription-Key', 'a731ccf0510849c690d23bb42ecef9d3')
.withHeaders('aeg-sas-key', 'b6LrYspQUAY2XnxkrDFDFDYsb8U2zqMQAzaQoZcQ=')
.withJson({ "product": "IRT", "entity": "CENTRE PROVISIONING AND RECIPIENT DETAILS", "operation": "UPDATE", "jobName": "AUTOPERF02", "studyId": "AUTO02" })
.expectStatus(201);
});
});
我认为您还需要等待request()
调用,或者使用 Cypress cy.request()
代替。
let token = "";
let authToken = "";
describe('POST /jobs', function () {
before(async function () {
var option = {
'method': 'POST',
'url': 'https://login.microsoftonline.com/<tenant_id>/oauth2/v2.0/token',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'client_id': `${userConfig.client_id}`,
'grant_type': 'password',
'Password': `${userConfig.Password}`,
'UserName': `${userConfig.UserName}`,
'scope': `${userConfig.scope}`,
'client_secret': `${userConfig.client_secret}`
}
};
await request(option, function (error, response) {
if (error) throw new Error(error)
const modifyResponse = JSON.parse(response.body)
token = modifyResponse["access_token"]
})
})
it('Create Job should return 201 status code', async () => {
authToken = token
...
使用cy.request
,您不必等待
cy.request(option)
.then(response => {
// if error, it's already thrown
token = response.body["access_token"]
})
使用 Mocha done() 表示请求已完成
以上async
仅适用于基于 Promise 的请求。
等待request(options, callback)
完成传入 Mocha 的done()
函数并在设置令牌后调用它。
这是一个简单的例子,使用 JSONPlaceholder 请求一些数据
const request = require('request');
let token;
before(function (done) {
request({
'method': 'GET',
'url': 'https://jsonplaceholder.typicode.com/todos/1'
}, function (error, response) {
const modifyResponse = JSON.parse(response.body)
token = modifyResponse.title
done() // signal end of request
})
})
it('sees the token', () => {
expect(token).to.eq('delectus aut autem') // passes
})
您可以使用 cypress 环境变量Cypress.env
来保存令牌,然后在整个测试过程中的任何地方使用它。
const {spec} = require('pactum')
const request = require('request')
const userConfig = require('../config/credential.json')
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
let token = ''
let authToken = ''
describe('POST /jobs', function () {
before(function () {
var option = {
method: 'POST',
url: 'https://login.microsoftonline.com/<tenant_id>/oauth2/v2.0/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
form: {
client_id: `${userConfig.client_id}`,
grant_type: 'password',
Password: `${userConfig.Password}`,
UserName: `${userConfig.UserName}`,
scope: `${userConfig.scope}`,
client_secret: `${userConfig.client_secret}`,
},
}
request(option, function (error, response) {
if (error) throw new Error(error)
const modifyResponse = JSON.parse(response.body)
//token = modifyResponse["access_token"]
Cypress.env('token', modifyResponse['access_token']) //Set the token in env variable
})
})
it('Create Job should return 201 status code', async () => {
authToken = Cypress.env('token') //Get the token from env variable
console.log('------------>', authToken)
await spec()
.post('https://localhost:3000/jobs')
.withHeaders('Authorization', `Bearer ${authToken}`)
.withHeaders('X-Client-Id', 'AzureDataLoaderUI')
.withHeaders('X-Message-Created-Ts', '2022-JUN-07 04:06')
.withHeaders('X-Message-Id', '4e8fb14c-c71f-46f8-b41a-561d393037ce')
.withHeaders('X-Transaction-Created-Ts', '2022-JUN-07 04:06')
.withHeaders('X-Transaction-Id', 'f11c97dc-a6eb-4ff7-aff6-de47c4686941')
.withHeaders('X-User-Id', 'AutoTestUser')
.withHeaders(
'Ocp-Apim-Subscription-Key',
'a731ccf0510849c690d23bb42ecef9d3'
)
.withHeaders('aeg-sas-key', 'b6LrYspQUAY2XnxkrDFDFDYsb8U2zqMQAzaQoZcQ=')
.withJson({
product: 'IRT',
entity: 'CENTRE PROVISIONING AND RECIPIENT DETAILS',
operation: 'UPDATE',
jobName: 'AUTOPERF02',
studyId: 'AUTO02',
})
.expectStatus(201)
})
})
您也可以在it()
块中使用function()
,并使用别名进行设置。
let authToken = "";
describe('POST /jobs', function () {
before(function () {
option = {...}
cy.request(option)
.then(response => {
token = response.body["access_token"]
})
.as('token') // alias will set "this.token"
})
it('Create Job should return 201 status code', async funtion() {
authToken = this.token // "this" can be used here
console.log('------------>', authToken)
猜猜专家已经回答了你的问题,因为你使用了 pactnum,这可以通过它来完成。
现在来解决这个问题,因为你在it
块中有一个回调,这就是它不起作用的原因。 但正如Fody
所说,专家们是正确的。
现在使用 pactnum,请按照以下步骤操作。
创建一个文件(名称可以是任何东西,例如测试文件夹中的_base.spec.js
)。
const userConfig = require('../config/credential.json') before(async function () { await spec() .post('https://login.microsoftonline.com/oauth2/v2.0/token') .withForm({ 'client_id': `${userConfig.client_id}`, 'grant_type': 'password', 'Password': `${userConfig.Password}`, 'UserName': `${userConfig.UserName}`, 'scope': `${userConfig.scope}`, 'client_secret': `${userConfig.client_secret}` }) .expectStatus(200) .stores('AUTH_TOKEN',"access_token") })
现在只需在您的代码中调用它
.post('https://<target_url>')
.withHeaders('Authorization', `Bearer $S{AUTH_TOKEN}`)
在这种情况下,因为你有单独的块,只需使用
authToken = token // no need for "this"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.