使用SuperTest和Jest来测试TypeScript Apollo Server。'request.post'不是一个函数

问题描述 投票:0回答:1

我试图使用SuperTest来测试一个Apollo服务器,按照第一个答案来测试 这个 Stack Overflow 问题,还有其他我找到的例子。

我的全部代码是

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

如果我改变我的代码,完全按照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

我用的是 ts-jest,并在Node 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'
};

感谢任何线索!

node.js typescript unit-testing jestjs supertest
1个回答
1
投票

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

import {default as request} from 'supertest';

request 现在是你可以调用的导出工厂函数。

const response = request('/graphql')
                    .post('/graphql')
...
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.