【问题标题】:Using SuperTest and Jest to test TypeScript Apollo Server: 'request.post' is not a function使用 SuperTest 和 Jest 测试 TypeScript Apollo Server:'request.post' 不是函数
【发布时间】:2020-09-14 04:06:02
【问题描述】:

在我找到的其他示例中,我正在尝试使用 SuperTest 来测试 this Stack Overflow question 的第一个答案之后的 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,并在 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】:

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

    import {default as request} from 'supertest';
    

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

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

    【讨论】:

      猜你喜欢
      • 2021-08-15
      • 2019-07-31
      • 2022-06-10
      • 1970-01-01
      • 2021-01-18
      • 2019-03-04
      • 1970-01-01
      • 2019-03-14
      • 2020-03-24
      相关资源
      最近更新 更多