我正在使用MochaJS和SuperTest在开发过程中测试我的API并且非常喜欢它.
但是,在将代码推送到生产环境之前,我还希望将这些相同的测试转换为远程测试我的临时服务器.
这是我使用的测试样本
request(app)
.get('/api/photo/' + photo._id)
.set(apiKeyName, apiKey)
.end(function(err, res) {
if (err) throw err;
if (res.body._id !== photo._id) throw Error('No _id found');
done();
});
Run Code Online (Sandbox Code Playgroud) 我正在使用supertest测试Node.js API ,我无法解释为什么res.body对象超集返回为空.数据显示在res.text对象中,但不是res.body,任何想法如何解决这个问题?
我正在使用Express和body-parser:
app.use(bodyParser.json());
app.use(bodyParser.json({ type: jsonMimeType }));
app.use(bodyParser.urlencoded({ extended: true }));
Run Code Online (Sandbox Code Playgroud)
这是我正在测试的API方法:
app.get(apiPath + '/menu', function(req, res) {
var expiration = getExpiration();
res.set({
'Content-Type': jsonMimeType,
'Content-Length': jsonTestData.length,
'Last-Modified': new Date(),
'Expires': expiration,
'ETag': null
});
res.json({ items: jsonTestData });
}
Run Code Online (Sandbox Code Playgroud)
以下是我针对此API方法执行的测试:
describe('GET /menu', function() {
describe('HTTP headers', function() {
it('responds with the right MIME type', function(done) {
request(app)
.get(apiPath + '/menu')
.set('Accept', 'application/vnd.burgers.api+json')
.expect('Content-Type', 'application/vnd.burgers.api+json; charset=utf-8')
.expect(200, done); …Run Code Online (Sandbox Code Playgroud) 例如,我必须在验收测试中测试服务器错误(Express),这些错误不能(或不应该)与响应一起发送
错误:发送后无法设置标头.
使用错误处理程序捕获错误并使用5XX代码进行响应将在此处提供有价值的反馈,但问题是已经发送了标头.
这种错误可能是非关键的,很难发现,通常它们是从日志中找出来的.
规格是
it('should send 200', function (done) {
request(app).get('/').expect(200, done);
});
Run Code Online (Sandbox Code Playgroud)
测试的应用程序是
app.get('/', function (req, res, next) {
res.sendStatus(200);
next();
});
app.use(function (req, res) {
res.sendStatus(200);
});
Run Code Online (Sandbox Code Playgroud)
app在类似情况下,Express 实例和请求测试库(即Supertest)之间进行通信的最合适方式是什么?
问题不仅限于Supertest.如果有包可以解决Supertest无法解决的问题,也可以考虑它们.
我正在使用超级测试测试快速服务器,并且我需要测试后调用。我认为帖子应该成功并返回状态 200,但它返回 401。有人告诉我,我需要通过帖子传递请求正文,但我不确定具体如何执行此操作。
我尝试使用 .send({name: 'aName'}) 但这给了我相同的 401 代码。
下面是app.js
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const hateoasLinker = require('express-hateoas-links');
const AValidator = require('./AValidator');
const BValidator = require('./BValidator');
const schema_v1 = require("./schema.json");
const {
logService: logger
} = require("@utils");
let aValidator = AValidator(schema_v1);
let ValidatorApi = BValidator.ValidatorApi('api');
let adminValidator = BValidator.ValidatorAdmin('admin');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(hateoasLinker);
app.post('/*/activate',admiValidator, (req, res) => {
console.log("In Activate===============>");
res.status(200);
res.json({
rel: "self",
method: "POST",
title: 'Activate Solution',
href: "/activate"
});
}); …Run Code Online (Sandbox Code Playgroud) 我用supertest测试我的Node.js应用程序.在我的控制器中,我访问会话对象.为了生成有效请求,此会话对象需要填充一些数据.
调节器
// determine whether it is user's own profile or not
var ownProfile = userId == req.session.user._id ? true : false;
Run Code Online (Sandbox Code Playgroud)
测试
it('profile', function (done) {
testUserOne.save(function(error, user){
request
.agent(server)
.get('/profile?userId=' + user._id)
.expect('Content-Type', /html/)
.expect(200)
.expect(/Profile/)
.end(done);
})
});
Run Code Online (Sandbox Code Playgroud)
题
如何模拟req/session对象?
我试图使用Node.js supertest来测试我编写的一些REST API.我需要发送一个等同于以下CURL请求的请求:
curl -X POST -F api_key=KEY -F image=@my_file http://localhost:3000/v1/upload
Run Code Online (Sandbox Code Playgroud)
我尝试了以下,但我得到了Uncaught TypeError: first argument must be a string or Buffer.
request.post('/v1/upload')
.type('form')
.field('api_key', 'abcd')
.attach('image', 'some path')
.end(function(err, res) {
res.body.error.should.equal('Invalid username/api_key.');
done();
});
Run Code Online (Sandbox Code Playgroud)
我也试过发送它:
request.post('/v1/upload')
.type('form')
.field('api_key', 'abcd')
.attach('image', 'some path')
.end(function(err, res) {
res.body.error.should.equal('Invalid username/api_key.');
done();
});
Run Code Online (Sandbox Code Playgroud)
但服务器只能解析文件上传请求而不是api_key.
Axios 和 Supertest 都可以向服务器发送 HTTP 请求。但为什么用Supertest来测试,而用axios来练习API调用呢?
使用supertest,我可以测试重定向代码302
var request = require('supertest');
var app = require('../server').app;
describe('test route', function(){
it('return 302', function(done){
request(app)
.get('/fail_id')
.expect(302, done);
});
it('redirect to /');
});
Run Code Online (Sandbox Code Playgroud)
我如何测试url objetive重定向?
如何使用正在发送的令牌测试文件上传?我返回“0”而不是确认上传。
这是一个失败的测试:
var chai = require('chai');
var expect = chai.expect;
var config = require("../config"); // contains call to supertest and token info
describe('Upload Endpoint', function (){
it('Attach photos - should return 200 response & accepted text', function (done){
this.timeout(15000);
setTimeout(done, 15000);
config.api.post('/customer/upload')
.set('Accept', 'application.json')
.send({"token": config.token})
.field('vehicle_vin', "randomVIN")
.attach('file', '/Users/moi/Desktop/unit_test_extravaganza/hardwork.jpg')
.end(function(err, res) {
expect(res.body.ok).to.equal(true);
expect(res.body.result[0].web_link).to.exist;
done();
});
});
});
Run Code Online (Sandbox Code Playgroud)
这是一个工作测试:
describe('Upload Endpoint - FL token ', function (){
this.timeout(15000);
it('Press Send w/out attaching photos returns error message', function (done){
config.api.post('/customer/upload') …Run Code Online (Sandbox Code Playgroud) 我刚刚开始学习使用 supertest 和 mocha 进行测试。我读过supertest的api文档,它说supertest支持superagent提供的所有较低级别的API。SuperAgent 说我们可以通过以下方式发送 formData 对象:
request.post('/user')
.send(new FormData(document.getElementById('myForm')))
.then(callback)
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用 supertest 发送 formData 对象时,如下所示:
server
.post('/goal_model/images/' + userId + '/' + tmid)
.set('Authorization',`Bearer ${token}`)
.send(formData)
.expect("Content-type",/json/)
.expect(201)
.end(function(err,res){
should(res.status).equal(201);
console.log(res.message);
done();
});
Run Code Online (Sandbox Code Playgroud)
其中 formData 是这样的:
let file;
let formData = new FormData();
let fn = "../../../Downloads/Images/5k.jpg";
formData.append("image", file);
Run Code Online (Sandbox Code Playgroud)
然后,当我尝试发送这个对象时,它只是说:
TypeError: "string" must be a string, Buffer, or ArrayBuffer
Run Code Online (Sandbox Code Playgroud)
是否可以通过这种方式发送 formData 对象?我做错了什么或者该怎么做?如果没有,为什么?我搜索了很多相关问题,但没有一个能解决我的问题。我现在真的很挣扎。
supertest ×10
node.js ×8
mocha.js ×5
javascript ×3
superagent ×2
testing ×2
axios ×1
chai ×1
endpoint ×1
express ×1
jestjs ×1
session ×1
unit-testing ×1