repetitions.test.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const bcrypt = require('../bcrypt');
  2. const EXPECTED = 2500; //number of times to iterate these tests.)
  3. const { TEST_TIMEOUT_SECONDS } = process.env;
  4. let timeout = 5e3; // default test timeout
  5. // it is necessary to increase the test timeout when emulating cross-architecture
  6. // environments (i.e. arm64 from x86-64 host) which have significantly reduced performance:
  7. if ( TEST_TIMEOUT_SECONDS )
  8. timeout = Number.parseInt(TEST_TIMEOUT_SECONDS, 10) * 1e3;
  9. jest.setTimeout(timeout);
  10. test('salt_length', () => {
  11. expect.assertions(EXPECTED);
  12. return Promise.all(Array.from({length: EXPECTED},
  13. () => bcrypt.genSalt(10)
  14. .then(salt => expect(salt).toHaveLength(29))));
  15. })
  16. test('test_hash_length', () => {
  17. expect.assertions(EXPECTED);
  18. const SALT = '$2a$04$TnjywYklQbbZjdjBgBoA4e';
  19. return Promise.all(Array.from({length: EXPECTED},
  20. () => bcrypt.hash('test', SALT)
  21. .then(hash => expect(hash).toHaveLength(60))));
  22. })
  23. test('test_compare', () => {
  24. expect.assertions(EXPECTED);
  25. const HASH = '$2a$04$TnjywYklQbbZjdjBgBoA4e9G7RJt9blgMgsCvUvus4Iv4TENB5nHy';
  26. return Promise.all(Array.from({length: EXPECTED},
  27. () => bcrypt.compare('test', HASH)
  28. .then(match => expect(match).toEqual(true))));
  29. })
  30. test('test_hash_and_compare', () => {
  31. expect.assertions(EXPECTED * 3);
  32. const salt = bcrypt.genSaltSync(4)
  33. return Promise.all(Array.from({length: EXPECTED},
  34. () => {
  35. const password = 'secret' + Math.random();
  36. return bcrypt.hash(password, salt)
  37. .then(hash => {
  38. expect(hash).toHaveLength(60);
  39. const goodCompare = bcrypt.compare(password, hash).then(res => expect(res).toEqual(true));
  40. const badCompare = bcrypt.compare('bad' + password, hash).then(res => expect(res).toEqual(false));
  41. return Promise.all([goodCompare, badCompare]);
  42. });
  43. }));
  44. }, timeout * 3);