简体   繁体   English

虽然循环不是随机生成数据

[英]While loop is not generating data randomly

I'm creating API tests with async-await using Supertest and Mocha. 我正在使用Supertest和Mocha使用async-await创建API测试。

In the accountsData.js file I created a function to generate random test accounts. accountsData.js文件中,我创建了一个用于生成随机测试帐户的函数。

In the accountsHelper.js file I created a function to create unlimited accounts using a while loop accountsHelper.js文件中,我创建了一个使用while循环创建无限账户的功能

When I run tests on the post_accounts.js file, the first account is created successfully, but from the second account, the data generated in the accountsData.js file is already repeated. 当我对post_accounts.js文件运行测试时,第一个帐户已成功创建,但是从第二个帐户开始, accountsData.js文件中生成的数据已经重复。

Why isn't data randomly generated when I create more than one account using data from the accountsData.js file? 当我使用accountsData.js文件中的数据创建多个帐户时,为什么不随机生成数据?

accountsData.js accountData.js

const casual = require('casual');


function randomAccount() {
  return {
    'email': casual.email,
    'password': '123456',
  };
}

module.exports = {
  randomAccount,
};

accountsHelper.js accountHelper.js

const request = require('supertest');
const commonData = require('../data/commonData');

/* eslint-disable no-console */

const accountList = [];
let counterAccounts;


module.exports = {

  async createAccount(account, accountsToCreate = 2, validateResponse = true) {
    counterAccounts = 0;
    while (counterAccounts < accountsToCreate) {
      try {
        const res = await request(commonData.environment.staging)
          .post(commonData.endpoint.accounts)
          .send(account);
        if (validateResponse === true) {
          if (res.status === commonData.statusCode.ok) {
            accountList.push(res.body);
          } else {
            throw new Error('Email already exists\n\n' + JSON.stringify(res.body, null, ' '));
          }
        } else {
          return res.body;
        }
      } catch (err) {
        console.log(err);
      }
      counterAccounts++;
    }
    return accountList;
  },
};

post_accounts.js post_accounts.js

const accountsData = require('../../data/accountsData');
const accountsHelper = require('../../helpers/accountsHelper');
const account = accountsData.randomAccount();

describe('Create accounts with email and password', () => {
  context('valid accounts', () => {
    it('should create an account successfully', async() => {
      const res = await accountsHelper.createAccount(account);
      // eslint-disable-next-line no-console
      console.log(res);
    });
  });
});

API response: API回应:

  Create accounts with email and password
    valid accounts
Error: Email already exists

{
 "error": {
  "statusCode": 422,
  "name": "ValidationError",
  "message": "The `account` instance is not valid. Details: `email` Email already exists (value: \"Lemuel.Lynch@Susan.net\").",
  "details": {
   "context": "account",
   "codes": {
    "email": [
     "uniqueness"
    ]
   },
   "messages": {
    "email": [
     "Email already exists"
    ]
   }
  }
 }
}
    at Object.createAccount (/Users/rafael/Desktop/projects/services/test/helpers/accountsHelper.js:24:19)
    at process._tickCallback (internal/process/next_tick.js:68:7)
[ { 'privacy-terms': false,
    'created-date': '2019-08-24T10:00:34.094Z',
    admin: false,
    isQueued: false,
    lastReleaseAttempt: '1970-01-01T00:00:00.000Z',
    'agreed-to-rules': { agreed: false },
    email: 'Lemuel.Lynch@Susan.net',
    id: '5d610ac213c07d752ae53d91' } ]
      ✓ should create an account successfully (2243ms)


  1 passing (2s)

The code that you posted doesn't correspond to the code that you're describing in prose. 您发布的代码与您在散文中描述的代码不符。

However, I tested your accountsData.js file, in the way that your words (but not your code) say that you're using it, and it works fine. 但是,我以您的文字(而不是您的代码)说出您正在使用它的方式测试了accountsData.js文件,并且它可以正常工作。

// main.js

const { createPerson } = require(__dirname + '/accountsData')

console.log(createPerson())
console.log(createPerson())
console.log(createPerson())
console.log(createPerson())
console.log(createPerson())

Output from running it once: 运行一次的输出:

$ node main.js
{ email: 'Anne_Ebert@Macie.com', password: '123456' }
{ email: 'Manley.Lindgren@Kshlerin.info', password: '123456' }
{ email: 'McClure_Thurman@Zboncak.net', password: '123456' }
{ email: 'Breitenberg.Alexander@Savannah.com', password: '123456' }
{ email: 'Keely.Mann@Stark.io', password: '123456' }

And again: 然后再次:

$ node main.js
{ email: 'Destany_Herman@Penelope.net', password: '123456' }
{ email: 'Narciso_Roob@gmail.com', password: '123456' }
{ email: 'Burnice_Rice@yahoo.com', password: '123456' }
{ email: 'Roma_Nolan@yahoo.com', password: '123456' }
{ email: 'Lilla_Beier@yahoo.com', password: '123456' }

Nothing in the code that you posted is actually requiring or using accountsData.js . 您发布的代码中的任何内容实际上都不需要或不使用accountsData.js If you change your code to use it, I think you'll see, like I do, that it works. 如果您更改代码以使用它,我想您会像我一样看到它起作用。

Problem is, you are generating the random account and storing it in a variable ' post_accounts.js(line 3) '. 问题是,您正在生成随机帐户,并将其存储在变量“ post_accounts.js(第3行) ”中。 So, when you create an account, you are using the same payload to create multiple accounts, which obviously throws an error. 因此,当您创建一个帐户时,您正在使用相同的有效负载来创建多个帐户,这显然会引发错误。

I just modified the accountHelper to properly handle your scenario. 我刚刚修改了accountHelper以正确处理您的情况。 Hope this helps. 希望这可以帮助。

Note: The code is not tested, I just wrote it from my mind. 注意:该代码未经测试,只是我脑子里写的。 Please test and let me know if it works. 请测试,让我知道它是否有效。

// accountsHelper.js

const request = require('supertest');
const commonData = require('../data/commonData');
const accountsData = require('../../data/accountsData');
/* eslint-disable no-console */

const accountList = [];

module.exports = {

  async createAccount(account, accountsToCreate = 1, validateResponse = true) {
    // creates an array of length passed in accountsToCreate param
    return (await Promise.all(Array(accountsToCreate)
      .fill()
      .map(async () => {
        try {
          const res = await request(commonData.environment.staging)
            .post(commonData.endpoint.accounts)
            // takes account if passed or generates a random account
            .send(account || accountsData.randomAccount());

          // validates and throw error if validateResponse is true
          if (validateResponse === true && (res.status !== commonData.statusCode.ok)) {
            throw new Error(
              'Email already exists\n\n' +
              JSON.stringify(res.body, null, ' ')
            );
          }

          // return response body by default
          return res.body;
        } catch (e) {
          console.error(e);
          // return null if the create account service errors out, just to make sure the all other create account call doesnt fail
          return null;
        }
      })))
      // filter out the null(error) responses
      .filter(acc => acc);
  }
};


//post_accounts.js

const accountsHelper = require('../../helpers/accountsHelper');
const accountsData = require('../../data/accountsData');

const GENERATE_RANDOM_ACCOUNT = null;

describe('Create accounts with email and password', () => {
  context('valid accounts', () => {
    it('should create an account successfully', async () => {
      const result = await accountsHelper.createAccount();

      expect(result.length).toEquals(1);
    });

    it('should create 2 accounts successfully', async () => {
      const result = await accountsHelper.createAccount(GENERATE_RANDOM_ACCOUNT, 2);

      expect(result.length).toEquals(2);
    });

    it('should not create duplicate accounts', async () => {
      const account = accountsData.randomAccount();
      // here we are trying to create same account twice
      const result = await accountsHelper.createAccount(account, 2);

      // expected result should be one as the second attempt will fail with duplicate account
      expect(result.length).toEquals(1);
    });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM