我有一個快速應用程式:
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors({ optionsSuccessStatus: 200 }));
app.get('/api/whoami', (req, res) => {
const ipaddress = req.ip;
res.status(200).json({ ipaddress });
});
app.listen(process.env.PORT || 3000);
module.exports = app;
和一個測驗檔案:
const chai = require('chai');
const chaiHttp = require('chai-http');
const chaiMatch = require('chai-match');
const { describe, it } = require('mocha');
const server = require('../../server');
const should = chai.should();
const { expect } = chai;
chai.use(chaiHttp);
chai.use(chaiMatch);
describe('/GET /api/whoami', () => {
it('should return the IP address', (done) => {
chai.request(server)
.get('/api/whoami')
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('ipaddress');
expect(res.body.ipaddress).should.match(/* very long regex */);
done();
});
});
});
出于某種原因,我不斷收到Uncaught AssertionError: expected Assertion{ __flags: { …(4) } } to match [my very long regex],我沒有找到任何有同樣錯誤的人。如何使用 express 獲取我的真實 IP?或者什么是測驗它的正確方法?
uj5u.com熱心網友回復:
語法是expect(something).to.match而不是expect(something).should.match。請參閱檔案。或者,如果您想使用should,則不需要expect,因為它的語法是something.should.match.
因此,解決方法是按如下方式更改您的代碼:
expect(res.body.ipaddress).to.match(/* very long regex */);
...或如下:
res.body.ipaddress.should.match(/* very long regex */);
在樣式指南中,您可以很好地比較how to useexpect和how to useshould。
通過混合這兩個東西,您將expect(...)回傳包含類似內容的物件to并將其用作您的源should,以便should.match檢查由回傳的物件expect(...)而不是 IP 地址本身。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/432068.html
