我在尝试学习如何测试next.js应用程序时收到此错误消息。我已尝试从配置顶部的utils和测试文件导入文本编码器,但没有成功
ReferenceError: TextEncoder is not defined
at Object.<anonymous> (node_modules/whatwg-url/lib/encoding.js:2:21)
at Object.<anonymous> (node_modules/whatwg-url/lib/url-state-machine.js:5:34)
at Object.<anonymous> (node_modules/whatwg-url/lib/URL-impl.js:2:13)
at Object.<anonymous> (node_modules/whatwg-url/lib/URL.js:442:14)
at Object.<anonymous> (node_modules/whatwg-url/webidl2js-wrapper.js:3:13)
at Object.<anonymous> (node_modules/whatwg-url/index.js:3:34)
at Object.<anonymous> (node_modules/mongodb-connection-string-url/src/index.ts:1:1)
at Object.<anonymous> (node_modules/mongodb/src/connection_string.ts:3:1)
at Object.<anonymous> (node_modules/mongodb/src/mongo_client.ts:11:1)
at Object.<anonymous> (node_modules/mongodb/src/change_stream.ts:17:1)
at Object.<anonymous> (node_modules/mongodb/src/index.ts:3:1)
at Object.<anonymous> (node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js:8:16)
at Object.<anonymous> (node_modules/mongoose/lib/drivers/node-mongodb-native/index.js:7:18)
at Object.<anonymous> (node_modules/mongoose/lib/index.js:7:25)
at Object.<anonymous> (node_modules/mongoose/index.js:8:18)
at Object.<anonymous> (library/mongoDB.js:15:56)
at Object.<anonymous> (library/players.js:15:18)
at Object.<anonymous> (pages/index.js:18:18)
at Object.<anonymous> (tests/index.test.js:6:53)
JEST配置文件
const nextJest = require('next/jest')
const createJestConfig = nextJest({
dir: './',
})
const customJestConfig = {
moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
}
module.exports = createJestConfig(customJestConfig)
Package.json
"devDependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"eslint": "8.23.1",
"eslint-config-next": "12.3.0",
"jest": "^29.1.1",
"jest-environment-jsdom": "^29.1.1"
}
Index.test.js
import Home from '../pages/index'
import '@testing-library/jest-dom'
import { fireEvent, render, screen } from '@testing-library/react'
describe('Home Page', () => {
it('renders home component',
() => {
render(<Home />)
expect(screen.getByTestId('home-page')).toBeInTheDocument()
})
})
1条答案
按热度按时间j91ykkif1#
我会在一个专用文件上模拟
TextEncoder
,该文件将作为设置文件放置在jest配置中。通过这种方式,我认为您应该消除那个错误。