我正在尝试使用以下代码测试我的节点API索引端点
index.test.js
const chai = require('chai')
const chaiHttp = require('chai-http')
const server = 'http://localhost:8000'
chai.use(chaiHttp)
describe('set up test', () => {
it('set up test', () => {
expect(1).toEqual(1)
})
})
describe('index route test', () => {
it('index route test', (done) => {
const { res } = chai
.request(server)
.get('/')
.end((res) => {
expect(res.statusCode).toBe(200)
done()
})
console.log(res)
})
})
1.我的失败测试'索引路由测试'通过,但它应该失败(解决)。
1.接收的响应未定义(我在控制台中记录)。
我的输出如下:
输出
> jest --forceExit || true
FAIL tests/index.test.js
set up test
✓ set up test (6 ms)
index route test
✕ gives welcome message (49 ms)
● index route test › gives welcome message
expect(received).toBe(expected) // Object.is equality
Expected: 200
Received: undefined
18 | .get('/')
19 | .end((res) => {
> 20 | expect(res.statusCode).toBe(200)
| ^
21 | done()
22 | })
23 | console.log(res)
at tests/index.test.js:20:32
at Test.Object.<anonymous>.Request.callback (node_modules/superagent/lib/node/index.js:728:3)
at ClientRequest.<anonymous> (node_modules/superagent/lib/node/index.js:647:10)
console.log
undefined
at Object.<anonymous> (tests/index.test.js:23:13)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 1.63 s, estimated 2 s
Ran all test suites.
Force exiting Jest: Have you considered using `--detectOpenHandles` to detect async operations that kept running after all tests finished?
我如何返回响应?
2条答案
按热度按时间332nm8kg1#
我没有得到任何响应通过传递应用程序的URL到服务器变量。因此,我将语法更改为ES6 import而不是require,并使用app模块而不是chai-http文档中的应用程序服务器URL
所以我的代码结构过渡到
这样,我就可以捕获响应并对其运行检查。我的测试通过了。输出为:
w8f9ii692#
accepted answer有点笨拙,混合了promise和
done()
,可以稍微清理一下。这里有一个改进,专门使用promise并使用async
/await
将回调平坦化,以将Assert降低到顶层:此外,
require
与import
应该没有关系。