1

设想

npm test过去可以毫无问题地工作。在大约一个月的时间里(我忽略了测试),有些东西发生了变化,现在我ReferenceError: document is not defined在尝试通过npm test.

即使document删除了这个错误也会出现,所以它看起来像是一个木偶问题,但我不确定为什么现在会出现。我检查了一个多月前的代码,测试仍然有效,但发生了很大变化,很难追查实际问题。

尝试的解决方案

  • 升级节点
  • 重新安装 npm 包
  • 恢复jest-puppeteer.config.js到以前的版本
  • 添加@jest-environment jsdom到修复文档问题但随后导致的测试ReferenceError: page is undefined

问题

如果不从头开始,我该如何解决这个问题?也就是说,我准备重新开始,如果这就是它所需要的,有时它会这样做。

代码

这是一个基本的笑话文件

import "core-js/stable";
import "regenerator-runtime/runtime";
import {Provider} from "react-redux"
import mockState from "./mocks/mockState"
import configureStore from "redux-mock-store"
import ShallowRenderer from 'react-test-renderer/shallow'
import API from '../src/API'
import getNavigationResponse from '../src/nocks/getNavigation'
import expectedNavigationState from "./static/expectedNavigationState"
import pageObjects from "./static/pageObjects"
import utils from './utils'
import constants from '../src/constants'


describe('API tests', () => {
    beforeEach(async() => {
        await page.goto('http://localhost:3000');
        await page.setViewport({ width: 900, height: 600 });
        await page.goto('http://localhost:3000/');
        await page.evaluate(() => {
            document.getElementById('root').classList.add('animated-test');
        });
        await page.waitForSelector(pageObjects.navFactory);
    });

    // PASS
    test('API data to be in store', async () => {
        await page.waitForSelector(pageObjects.primaryNavLink);

        // get state from root
        const store = await utils.getStore();

        expect(store[0].navigation.urlHashMap).toEqual(expectedNavigationState);
    });

    test.todo('Make sure content==true on vanity urls (home)')

    test.todo('Make sure content==false on url items with children (visitor)')

    // PASS
    test('API cancel should cancel the API request', async () => {
        API.dispatch = () => {

        };
        API.fetch(constants.NAVIGATION_HREF, 'API_FETCH_TYPE_NAVIGATION');
        const promiseCanceled = API.cancel('API_FETCH_TYPE_NAVIGATION');
        expect(promiseCanceled).hasOwnProperty('promise');
        expect(promiseCanceled).hasOwnProperty('cancel');
    });
});

** 编辑 **

据我所知,这个“ReferenceError”似乎是一个babel错误,因为babel似乎无法弄清楚“document”是什么。我追踪了问题发生的位置,并且它在第三方插件中,所以我同时在开发人员的 github 页面上留下了一个注释。目前我的“解决方案”是评论这个测试 - 当我有时间找到合适的解决方案时,我会再次投入更多精力

** 编辑 2 **

如果我添加<rootDir>/node_modules/react-json-view/dist/main.js到 babel config'stransformIgnorePatterns那么我会得到一个不同的错误

ReferenceError: regeneratorRuntime is not defined

这很奇怪,因为我明确地import "regenerator-runtime/runtime"在顶部。这似乎更近了一步,但我不确定。我切换回babel-polyfill(不推荐使用)只是为了尝试它,但以不同的错误结束TypeError: jest: failed to cache transform results

4

1 回答 1

0

通常你可以做类似这个答案的事情,即添加:

npm test --env=jsdom

但是由于我还需要 Puppeteer 的环境,所以存在冲突,因为节点似乎只支持 ONE 环境。

最终我删除了有问题的插件。

于 2020-08-19T22:45:06.943 回答