index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict';
  2. var _vm;
  3. function _load_vm() {
  4. return _vm = _interopRequireDefault(require('vm'));
  5. }
  6. var _jestUtil;
  7. function _load_jestUtil() {
  8. return _jestUtil = require('jest-util');
  9. }
  10. var _jestMock;
  11. function _load_jestMock() {
  12. return _jestMock = _interopRequireDefault(require('jest-mock'));
  13. }
  14. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  15. class NodeEnvironment {
  16. constructor(config) {
  17. this.context = (_vm || _load_vm()).default.createContext();
  18. const global = this.global = (_vm || _load_vm()).default.runInContext('this', Object.assign(this.context, config.testEnvironmentOptions));
  19. global.global = global;
  20. global.clearInterval = clearInterval;
  21. global.clearTimeout = clearTimeout;
  22. global.Promise = Promise;
  23. global.setInterval = setInterval;
  24. global.setTimeout = setTimeout;
  25. (0, (_jestUtil || _load_jestUtil()).installCommonGlobals)(global, config.globals);
  26. this.moduleMocker = new (_jestMock || _load_jestMock()).default.ModuleMocker(global);
  27. const timerIdToRef = id => ({
  28. id,
  29. ref() {
  30. return this;
  31. },
  32. unref() {
  33. return this;
  34. }
  35. });
  36. const timerRefToId = timer => {
  37. return timer && timer.id || null;
  38. };
  39. const timerConfig = {
  40. idToRef: timerIdToRef,
  41. refToId: timerRefToId
  42. };
  43. this.fakeTimers = new (_jestUtil || _load_jestUtil()).FakeTimers({
  44. config,
  45. global,
  46. moduleMocker: this.moduleMocker,
  47. timerConfig
  48. });
  49. }
  50. setup() {
  51. return Promise.resolve();
  52. }
  53. teardown() {
  54. if (this.fakeTimers) {
  55. this.fakeTimers.dispose();
  56. }
  57. this.context = null;
  58. this.fakeTimers = null;
  59. return Promise.resolve();
  60. }
  61. // Disabling rule as return type depends on script's return type.
  62. /* eslint-disable flowtype/no-weak-types */
  63. runScript(script) {
  64. /* eslint-enable flowtype/no-weak-types */
  65. if (this.context) {
  66. return script.runInContext(this.context);
  67. }
  68. return null;
  69. }
  70. } /**
  71. * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  72. *
  73. * This source code is licensed under the MIT license found in the
  74. * LICENSE file in the root directory of this source tree.
  75. *
  76. *
  77. */
  78. module.exports = NodeEnvironment;