我不使用快递,而是使用koa js 1.0。 这是一个用于插入用户的示例应用程序。 它包括用于测试目的的超级摩卡咖啡。
在app.js - >
var koa = require('koa');
var app = koa();
var routes = require('koa-route');
//routes
var userRoutes = require("./userRoutes.js");
app.use(routes.post("/user",userRoutes.add);
app.use(routes.get("/user/:id",userRoutes.get);
module.exports = app;
app.listen(3000);
console.log('Listening to port 3000');
在userRoutes.js - >
中var parse = require('co-body');
var monk = require('monk');
var wrap = require('co-monk');
var db = monk("localhost/usersApi");
var users = wrap(db.get("users"));
module.exports.users = users;
module.exports.add = function *(){
var postedUser = yield parse(this);
var insertedUser = yield db.users.insert(postedUser);
this.set("location","/user/" + insertedUser._id);
this.status = 200;
};
module.exports.get = function *(id){
this.body = "You passed me: " + id;
};
在test.js - >
中var app = require('./app.js');
var request = require('supertest').agent(app.listen());
describe('Simple User Api:',function () {
var test_user = {name:'Marcus',City:'Bandung,Indonesia'};
it('creates a new user',function (done) {
//Post
request
.post('/user')
.send(test_user)
.expect('location',/^\/user\/[0-9a-fA-F]{24}$/)
.expect(200,done);
});
});
在package.json中 -
"scripts": {
"start": "node --harmony app.js",
"test": "mocha --harmony test.js -u bdd -R spec"
},
当我运行“npm test”命令时 它给出了以下错误:
Listening to port 3000
Simple User Api:
TypeError: Cannot read property 'insert' of undefined
at Object.module.exports.add (D:\Nodejs\KoaCRUD\userRoutes.js:17:38)
at next (native)
at Object.<anonymous> (D:\Nodejs\KoaCRUD\node_modules\koa-
route\index.js:34:19)
at next (native)
at Object.<anonymous>
(D:\Nodejs\KoaCRUD\node_modules\koa\node_modules\koa-compos
e\index.js:28:19)
at next (native)
at onFulfilled (D:\Nodejs\KoaCRUD\node_modules\co\index.js:65:19)
at process._tickCallback (node.js:369:9)
1) creates a new user
0 passing (220ms)
1 failing
1) Simple User Api: creates a new user:
Error: expected "location" header field
at Test._assertHeader
(D:\Nodejs\KoaCRUD\node_modules\supertest\lib\test.js:219:45)
at Test._assertFunction
(D:\Nodejs\KoaCRUD\node_modules\supertest\lib\test.js:265
:11)
at Test.assert
(D:\Nodejs\KoaCRUD\node_modules\supertest\lib\test.js:153:18)
at assert (D:\Nodejs\KoaCRUD\node_modules\supertest\lib\test.js:131:12)
at D:\Nodejs\KoaCRUD\node_modules\supertest\lib\test.js:128:5
at Test.Request.callback
(D:\Nodejs\KoaCRUD\node_modules\supertest\node_modules\s
uperagent\lib\node\index.js:603:3)
at IncomingMessage.<anonymous>
(D:\Nodejs\KoaCRUD\node_modules\supertest\node_mod
ules\superagent\lib\node\index.js:767:18)
at endReadableNT (_stream_readable.js:921:12)
npm ERR! Test failed. See above for more details.
我搜索了很多,但错误未解决。 谁知道问题是什么?提前谢谢。
答案 0 :(得分:1)
您似乎只是在 userRoutes.js
中犯了一个小错误该行:
var insertedUser = yield db.users.insert(postedUser);
应该是:
var insertedUser = yield users.insert(postedUser);
db 是你的monk变量,你已经用co-monk包装了它,所以你只需要使用 users.insert ,而不是 db.users。插入