Reputation: 95
I am getting this error message while trying to learn how to test next.js applications I have tried import the Text Encoder from utils at the top of the config as well as test file with no success
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 Config File
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()
})
})
Upvotes: 4
Views: 5751
Reputation: 414
I would do it by mocking TextEncoder
on a dedicated file which will be placed as a setup file on jest config.
This way I think you should get rid of that error.
// text-encoder.mock.ts
import { TextEncoder } from 'util';
global.TextEncoder = TextEncoder;
// jest.config.ts
const nextJest = require('next/jest');
const createJestConfig = nextJest({
dir: './',
});
const customJestConfig = {
moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
setupFiles: [
'<rootDir>/path/to/text-encoder.mock.ts',
],
};
module.exports = createJestConfig(customJestConfig)
Upvotes: 5