Cer*_*ean 6 javascript unit-testing typescript supertest jestjs
我正在使用 Jest 和 SuperTest 测试 Apollo 服务器。服务器是用 TypeScript 编写的,所以我使用ts-jest. 我需要将 SuperTest 绑定到特定端口。SuperTest 文档说
\n\n\n您可以将 http.Server 或函数传递给 request() - 如果服务器尚未侦听连接,则它会为您绑定到临时端口,因此无需跟踪端口。
\n
所以我想传递我的应用程序。我已经设置了索引文件来导出 Apollo 服务器
\n\n// index.ts\nimport { ApolloServer } from \'apollo-server\';\n...\nconst start = () => {\n ...\n const server = new ApolloServer(config);\n server.listen().then(({ url }) => {\n log.info(`interface server Running at ${url}`);\n });\n return server;\n};\n\nconst app = start();\n\nexport default app;\nRun Code Online (Sandbox Code Playgroud)\n\n但是当我运行我的代码时
\n\n// __test__/index.ts\nimport { default as request } from \'supertest\';\nimport log from \'../util/log\';\nimport app from \'../index\';\n\nlet postData = {\n query: `query allArticles {\n allArticles {\n id\n }\n }`,\n operationName: \'allArticles\'\n};\n\ntest(\'basic\', async () => {\n try {\n const response = await request(app)\n .post(\'/graphql\')\n .send(postData)\n .expect(200); // status code that you expect to be returned\n log.info(\'response\', response.statusCode);\n } catch (error) {\n log.info(`error ${error.toString()}`);\n }\n});\nRun Code Online (Sandbox Code Playgroud)\n\n我明白了
\n\n FAIL __test__/index.test.ts\n \xe2\x97\x8f Test suite failed to run\n\n Details:\n\n /Users/abc/Documents/projects/yaa-interface-new/index.js:1\n import { ApolloServer } from "apollo-server";\n ^^^^^^\n\n SyntaxError: Cannot use import statement outside a module\n\n 1 | import { default as request } from \'supertest\';\n 2 | import log from \'../util/log\';\n > 3 | import app from \'../index\';\n | ^\nRun Code Online (Sandbox Code Playgroud)\n\n由于某种原因,笑话正在寻找/index.js而不是index.ts?(js文件应该全部进入/dist- 见tsconfig下文)。根据这个 Stack Overflow 问题,我需要将 Babel 添加到 Jest 中。我尝试过设置 ts-jest 和 Jest 来使用 Babel,但我承认我不清楚我在做什么。无论如何,我都会遇到同样的错误。任何线索非常感谢!
我的jest.config.js:
// jest.config.js\nmodule.exports = {\n preset: \'ts-jest/presets/js-with-babel\',\n testEnvironment: \'node\',\n globals: {\n \'ts-jest\': {\n babelConfig: true\n }\n }\n};\nRun Code Online (Sandbox Code Playgroud)\n\n和我的tsconfig.json:
// tsconfig.json\n{\n "compilerOptions": {\n "target": "ES6",\n "lib": [\n "esnext",\n "dom"\n ],\n "skipLibCheck": true,\n "outDir": "dist",\n "strict": false,\n "forceConsistentCasingInFileNames": true,\n "esModuleInterop": true,\n "module": "commonjs",\n "moduleResolution": "node",\n "resolveJsonModule": true,\n "isolatedModules": true,\n "sourceMap": true,\n "alwaysStrict": true\n },\n "exclude": [\n "node_modules",\n "**/*.test.ts",\n "**/*.mock.ts"\n ]\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1003 次 |
| 最近记录: |