【发布时间】:2020-11-16 01:07:57
【问题描述】:
场景
npm test 以前可以正常工作。在大约一个月的时间里(我忽略了测试)发生了一些变化,现在我在尝试通过npm test 运行 Jest-Puppeteer 测试时收到了ReferenceError: document is not defined。
即使删除了document,也会出现此错误,因此这似乎是一个木偶问题,但我不确定为什么现在会出现这种情况。我检查了一个多月前的代码,测试仍然有效,但发生了很大变化,很难追查实际问题。
尝试的解决方案
- 升级节点
- 重新安装 npm 包
- 将
jest-puppeteer.config.js恢复到以前的版本 - 将
@jest-environment jsdom添加到修复文档问题但随后导致ReferenceError: page is undefined的测试
问题
如果不从头开始,我该如何解决这个问题?话虽如此,我已经准备好重新开始,如果这就是它所需要的,有时它会这样做。
代码
这是一个基本的 jest 文件
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 的 transformIgnorePatterns 中,则会收到不同的错误
ReferenceError: regeneratorRuntime is not defined
这很奇怪,因为我在顶部明确有 import "regenerator-runtime/runtime"。这似乎更近了一步,但我不确定。我切换回 babel-polyfill(已弃用)只是为了尝试它,但以 TypeError: jest: failed to cache transform results 的不同错误结束。
【问题讨论】:
标签: reactjs puppeteer jest-puppeteer