Использование SuperTest и Jest для тестирования TypeScript Apollo Server: 'request.post' не является функцией - PullRequest
0 голосов
/ 27 мая 2020

Я пытаюсь использовать 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 Ответ

1 голос
/ 27 мая 2020

supertest не имеет экспорта, поэтому необходимо изменить ваш импорт на

import {default as request} from 'supertest';

request теперь является экспортируемой фабричной функцией, которую вы можете вызвать:

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