等待在Jest测试中定义窗口/全局变量

时间:2019-08-19 19:13:36

标签: javascript jestjs

// index.html
// this script defines window.externalLibrary variable to use throughout app, 
// it just takes a second or few to load as "window.externalLibrary" is always undefined on startup
<script src="https://www.something.com/externalLibrary.js"></script>

// package.json
jest": {
    "setupFiles": [
      "./src/jest/globals.js"
    ]

// globals.js
global.externalLibrary = window.externalLibrary;

// externalLibraryTest.js
describe('externalLibrary.js Tests', () => {
  it('Please work', () => {
    console.log(window.externalLibrary);  //undefined
    console.log(global.externalLibrary); //undefined too
  });

如何使它正常工作?

通常在我的应用中,在使用变量之前,我会先加载一个函数:

export const initializeExternalLibrary = () => {
  return new Promise((resolve) => {
    if (window.singularApp) resolve(window.singularApp);
    Object.defineProperty(window, 'singularApp', {
      set (value) {
        console.log('External Library Initialized.');
        resolve(value);
      }
    });
  });
};

但是我尝试在Jest测试中使用该功能,但效果也不佳。有人有什么想法吗?我有点绝望,谢谢

0 个答案:

没有答案