我正在使用Jest和SuperTest测试Apollo服务器。服务器是用TypeScript编写的,因此我正在使用ts-jest
。我需要将SuperTest绑定到特定端口。 SuperTest文档说
您可以将http.Server或Function传递给request()-如果 服务器尚未在侦听连接,则将其绑定到 临时端口,因此您无需跟踪端口。
所以我想传递我的应用程序。我已经设置了索引文件以导出Apollo服务器
// 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;
但是,当我运行代码时
// __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()}`);
}
});
我知道
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';
| ^
出于某种原因,玩笑正在寻找/index.js
而不是index.ts
吗? (js
文件应全部放入/dist
中-参见下面的tsconfig
)。根据{{3}},我需要将Babel添加到Jest。我尝试同时设置ts-jest和Jest以使用Babel,但我承认我不清楚自己在做什么。无论如何,我都会遇到相同的错误。任何线索都值得赞赏!
我的jest.config.js
:
// jest.config.js
module.exports = {
preset: 'ts-jest/presets/js-with-babel',
testEnvironment: 'node',
globals: {
'ts-jest': {
babelConfig: true
}
}
};
和我的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"
]
}