使用 SuperTest 和 Jest 测试 TypeScript Apollo Server:'request.post' 不是函数

Using SuperTest and Jest to test TypeScript Apollo Server: 'request.post' is not a function

我正在尝试使用 SuperTest 来测试 Apollo 服务器,这是在 this Stack Overflow question 的第一个答案之后,以及我找到的其他示例。

我的完整代码是

//     /__test__/index.test.ts

import * as request from 'supertest';

    let postData = {
        query: `query allArticles{
                    allArticles{
                        id
                    }
                }`,
        operationName: 'allArticles'
    };

    test('basic', async () => {
        try {
            const response = request
                .post('/graphql')
                .send(postData)
                .expect(200); // status code that you expect to be returned
            console.log('response', response);
        } catch (error) {
            console.log(`error ${error.toString()}`);
        }
    });

然而当我 运行 这与 Jest

"test": "jest --detectOpenHandles --colors"

我明白了

 PASS  __test__/index.test.ts
  ● Console

    console.log
    error TypeError: request.post is not a function

      at __test__/index.test.ts:20:11

就其价值而言,我不认为这是 "passing" 测试,因为我在 expect 中输入什么并不重要。

如果我更改我的代码以完全遵循 Stack Overflow(将 GraphQL 端点直接传递给请求

  test('basic', async () => {
            try {
                const response = request('/graphql')
                    .post('/graphql')
                    .send(postData)
                    .expect(200); // status code that you expect to be returned
                console.log('response', response);
            } catch (error) {
                console.log(`error ${error.toString()}`);
            }
        });

我明白了

PASS  __test__/index.test.ts
  ● Console

    console.log
      error TypeError: request is not a function

      at __test__/index.test.ts:20:11

我在 Node 12.14

下使用 ts-jest 和 运行ning

我的 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"
  ]
}

我的jest.config

module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'node'
};

感谢任何线索!

supertest 没有导出,这就是为什么需要将导入更改为

import {default as request} from 'supertest';

request 现在是您可以调用的导出工厂函数:

const response = request('/graphql')
                    .post('/graphql')
...