在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:chaijs/chai-http开源软件地址:https://github.com/chaijs/chai-http开源编程语言:JavaScript 89.7%开源软件介绍:Chai HTTP
Features
InstallationThis is an addon plugin for the Chai Assertion Library. Install via npm.
PluginUse this plugin as you would all other Chai plugins. const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp); To use Chai HTTP on a web page, just include the <script src="chai.js"></script>
<script src="chai-http.js"></script>
<script>
chai.use(chaiHttp);
</script> Integration TestingChai HTTP provides an interface for live integration testing via superagent. To do this, you must first construct a request to an application or url. Upon construction you are provided a chainable api that allows you to specify the http VERB request (get, post, etc) that you wish to invoke. Application / ServerYou may use a function (such as an express or connect app) or a node.js http(s) server as the foundation for your request. If the server is not running, chai-http will find a suitable port to listen on for a given test. Note: This feature is only supported on Node.js, not in web browsers. chai.request(app)
.get('/') When passing an const requester = chai.request(app).keepOpen()
Promise.all([
requester.get('/a'),
requester.get('/b'),
])
.then(responses => { /* ... */ })
.then(() => requester.close()) URLYou may also use a base url as the foundation of your request. chai.request('http://localhost:8080')
.get('/') Setting up requestsOnce a request is created with a given VERB (get, post, etc), you chain on these additional methods to create your request:
Examples:
// Set a request header
chai.request(app)
.put('/user/me')
.set('Content-Type', 'application/json')
.send({ password: '123', confirmPassword: '123' })
// Send some JSON
chai.request(app)
.put('/user/me')
.send({ password: '123', confirmPassword: '123' })
// Send some Form Data
chai.request(app)
.post('/user/me')
.type('form')
.send({
'_method': 'put',
'password': '123',
'confirmPassword': '123'
})
// Attach a file
chai.request(app)
.post('/user/avatar')
.attach('imageField', fs.readFileSync('avatar.png'), 'avatar.png')
// Authenticate with Basic authentication
chai.request(app)
.get('/protected')
.auth('user', 'pass')
// Authenticate with Bearer Token
chai.request(app)
.get('/protected')
.auth(accessToken, { type: 'bearer' })
// Chain some GET query parameters
chai.request(app)
.get('/search')
.query({name: 'foo', limit: 10}) // /search?name=foo&limit=10 Dealing with the response - traditionalIn the following examples we use Chai's Expect assertion library: const { expect } = chai; To make the request and assert on its response, the chai.request(app)
.put('/user/me')
.send({ password: '123', confirmPassword: '123' })
.end((err, res) => {
expect(err).to.be.null;
expect(res).to.have.status(200);
}); CaveatBecause the For example, in the Mocha test framework, this is
accomplished using the
it('fails, as expected', function(done) { // <= Pass in done callback
chai.request('http://localhost:8080')
.get('/')
.end((err, res) => {
expect(res).to.have.status(123);
done(); // <= Call done to signal callback end
});
});
it('succeeds silently!', () => { // <= No done callback
chai.request('http://localhost:8080')
.get('/')
.end((err, res) => {
expect(res).to.have.status(123); // <= Test completes before this runs
});
}); When Dealing with the response - PromisesIf chai.request(app)
.put('/user/me')
.send({ password: '123', confirmPassword: '123' })
.then((res) => {
expect(res).to.have.status(200);
})
.catch((err) => {
throw err;
}); Note: Some older web browsers do not have native promise support. You can use any spec compliant library, such as:
// Add promise support if this does not exist natively.
if (!global.Promise) {
global.Promise = require('q');
}
const chai = require('chai');
chai.use(require('chai-http')); Retaining cookies with each requestSometimes you need to keep cookies from one request, and send them with the
next (for example, when you want to login with the first request, then access an authenticated-only resource later). For this, // Log in
const agent = chai.request.agent(app)
agent
.post('/session')
.send({ username: 'me', password: '123' })
.then((res) => {
expect(res).to.have.cookie('sessionid');
// The `agent` now has the sessionid cookie saved, and will send it
// back to the server in the next request:
return agent.get('/user/me')
.then((res) => {
expect(res).to.have.status(200);
});
}); Note: The server started by AssertionsThe Chai HTTP module provides a number of assertions
for the .status (code)
Assert that a response has a supplied status. expect(res).to.have.status(200); .header (key[, value])
Assert that a Note: When running in a web browser, the same-origin policy only allows Chai HTTP to read certain headers, which can cause assertions to fail. expect(req).to.have.header('x-api-key');
expect(req).to.have.header('content-type', 'text/plain');
expect(req).to.have.header('content-type', /^text/); .headersAssert that a Note: When running in a web browser, the same-origin policy only allows Chai HTTP to read certain headers, which can cause assertions to fail. expect(req).to.have.headers; .ipAssert that a string represents valid ip address. expect('127.0.0.1').to.be.an.ip;
expect('2001:0db8:85a3:0000:0000:8a2e:0370:7334').to.be.an.ip; .json / .text / .htmlAssert that a expect(req).to.be.json;
expect(req).to.be.html;
expect(req).to.be.text; .charsetAssert that a expect(req).to.have.charset('utf-8'); .redirectAssert that a expect(res).to.redirect;
expect(res).to.not.redirect; .redirectTo
Assert that a expect(res).to.redirectTo('http://example.com');
expect(res).to.redirectTo(/^\/search\/results\?orderBy=desc$/); .param
Assert that a expect(req).to.have.param('orderby');
expect(req).to.have.param('orderby', 'date');
expect(req).to.not.have.param('limit'); .cookie
Assert that a expect(req).to.have.cookie('session_id');
expect(req).to.have.cookie('session_id', '1234');
expect(req).to.not.have.cookie('PHPSESSID');
expect(res).to.have.cookie('session_id');
expect(res).to.have.cookie('session_id', '1234');
expect(res).to.not.have.cookie('PHPSESSID'); Releasing
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论