【发布时间】: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