ReactJS Jest Puppeteer测试不再起作用:ReferenceError:未定义文档

时间:2020-07-26 16:31:43

标签: reactjs puppeteer jest-puppeteer

场景

npm test可以正常工作。在一个月左右的时间(我忽略了测试)中,发生了一些变化,现在当我尝试通过ReferenceError: document is not defined运行Jest-Puppeteer测试时收到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似乎无法弄清楚“文档”是什么引起的。我跟踪了问题发生的地方,并且它在第三方插件中,所以在此期间,我在开发人员的github页面上留下了注释。目前,我的“解决方案”是对此测试进行评论-当我有时间找到合适的解决方案时,我会再次加大力度

**编辑2 **

如果我将<rootDir>/node_modules/react-json-view/dist/main.js添加到babel config的transformIgnorePatterns中,则会收到不同的错误

ReferenceError: regeneratorRuntime is not defined

这很奇怪,因为我明确地在顶部有import "regenerator-runtime/runtime"。这似乎离我们更近了,但我不确定。我切换回babel-polyfill(已弃用)只是为了尝试,但最后遇到了另一个错误TypeError: jest: failed to cache transform results

1 个答案:

答案 0 :(得分:0)

通常,您可以执行类似this answer的操作:

npm test --env=jsdom

但是由于我还需要Puppeteer的环境,因此发生冲突,因为节点似乎仅支持一个环境。

最终,我删除了出现问题的插件。