supertest
supertest copied to clipboard
TypeError: require(...) is not a function error
My Express App is
// index.ts
import express from 'express';
const app = express();
app.get('/', (req, res) => {
res.status(200);
});
app.listen(3000);
export default app;
and test is
import request from 'supertest';
import app from '../index';
describe('/', () => {
it ('header', (done) => {
request(app)
.get('/')
.then(response => {
console.log('response');
expect(response.status).toBe(200);
done();
})
.catch(err => {
console.log('response err', err);
})
});
});
dependency list:
- "express": "^4.17.1",
- "jest": "^25.1.0"
- "supertest": "^4.0.2"
- "ts-jest": "^25.2.1"
- "typescript": "^3.8.3"
- ...
babel.config.js
{
"presets": [
"@babel/env",
"@babel/preset-typescript"
],
"plugins": [
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-runtime"
]
}
jest.config.js
module.exports = {
verbose: true,
browser: true,
collectCoverage: true,
testEnvironment: 'node',
testRegex: '(/test/.*\\.test.[jt]s)$',
transform: {
'^.+\\.ts$': 'ts-jest',
},
coverageReporters: ['text'],
globals: {
window: true
}
}
tsconfig.json
{
"compilerOptions": {
"module": "es2020",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"target": "es2020",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
},
}
Run the test, after turn on the server
Here is result ...

and iconv-lite code line:

what is wrong?
I don't think this error is caused by supertest, as all this library does is to perform bare http requests and allow you to assert over the response. That is all. Try reproducing it in isolation (without supertest).
Yes, I had have the same issue @kkh975 @jonathansamines. The unique solution that I found is that all requires must be at the top of the file. In your case, you depend on iconv-lite library.