我试图使用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'
};
感谢任何线索!
supertest
没有导出,这就是为什么需要将你的导入改为
import {default as request} from 'supertest';
request
现在是你可以调用的导出工厂函数。
const response = request('/graphql')
.post('/graphql')
...