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

时间:2020-05-27 07:28:54

标签: node.js typescript unit-testing jestjs supertest

在发现this Stack Overflow question的第一个答案之后,我正在尝试使用SuperTest测试Apollo服务器。

我的完整代码是

//     /__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

对于它的价值,我不认为它正在“通过”测试,因为我放入expect中的内容并不重要。

如果我更改代码以完全遵循堆栈溢出(直接将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

我正在使用ts-jest,并在节点12.14下运行

我的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'
};

任何线索都值得赞赏!

1 个答案:

答案 0 :(得分:2)

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

supertest

import {default as request} from 'supertest'; 现在是您可以调用的导出工厂功能:

request
相关问题