I'm working on testing an Apollo Server using Jest and SuperTest. The server is written in TypeScript, so I'm using ts-jest. I need to bind SuperTest to a particular port. The SuperTest docs say
You may pass an http.Server, or a Function to request() - if the server is not already listening for connections then it is bound to an ephemeral port for you so there is no need to keep track of ports.
so I want to pass in my app. I've set up my index file to export the Apollo Server
// index.ts
import { ApolloServer } from 'apollo-server';
...
const start = () => {
...
const server = new ApolloServer(config);
server.listen().then(({ url }) => {
log.info(`interface server 📡 Running at ${url}`);
});
return server;
};
const app = start();
export default app;
However when I run my code
// __test__/index.ts
import { default as request } from 'supertest';
import log from '../util/log';
import app from '../index';
let postData = {
query: `query allArticles {
allArticles {
id
}
}`,
operationName: 'allArticles'
};
test('basic', async () => {
try {
const response = await request(app)
.post('/graphql')
.send(postData)
.expect(200); // status code that you expect to be returned
log.info('response', response.statusCode);
} catch (error) {
log.info(`error ${error.toString()}`);
}
});
I get
FAIL __test__/index.test.ts
â—Ź Test suite failed to run
Details:
/Users/abc/Documents/projects/yaa-interface-new/index.js:1
import { ApolloServer } from "apollo-server";
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import { default as request } from 'supertest';
2 | import log from '../util/log';
> 3 | import app from '../index';
| ^
For some reason jest is looking in /index.js instead of index.ts ? (The js files should all be going into /dist-- see tsconfig below). According to this Stack Overflow question, I need to add Babel to Jest. I've tried to set up both ts-jest and Jest to use Babel but I confess I am unclear what I'm doing. In any case, I get the same error. Any clues much appreciated!
My jest.config.js:
// jest.config.js
module.exports = {
preset: 'ts-jest/presets/js-with-babel',
testEnvironment: 'node',
globals: {
'ts-jest': {
babelConfig: true
}
}
};
and my tsconfig.json:
// tsconfig.json
{
"compilerOptions": {
"target": "ES6",
"lib": [
"esnext",
"dom"
],
"skipLibCheck": true,
"outDir": "dist",
"strict": false,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"module": "commonjs",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"sourceMap": true,
"alwaysStrict": true
},
"exclude": [
"node_modules",
"**/*.test.ts",
"**/*.mock.ts"
]
}