javascript - 在 chai 中进行单元测试时无法读取未定义的属性“应用”
问题描述
试图测试一个简单的快速休息,我得到
Uncaught TypeError: Cannot read property 'apply' of undefined at Immediate.<anonymous> (node_modules/express/lib/router/index.js:635:15)
不知道我做错了什么。
我引用了类似的线程,但它并不特定于单元测试
参考这个
https://codehandbook.org/unit-test-express-route/
router.spec.js
import chai from 'chai';
import chaiHttp from 'chai-http';
import router from '../routes/';
chai.use(chaiHttp);
chai.should();
const expect = chai.expect();
describe('index page should render, hello world', () => {
it('should render hello world 200', (done) => {
chai.request(router).get('/').end( (err, res) => {
expect(200, "ok").
expect(res.text).to.equal('Hello World');
done();
})
})
})
index.js
import express from 'express';
const router = express.Router();
router.get('/', (req, res) => {
return res.status(200).json({
message: "Hello World"
})
})
export default router;
.babelrc
{
"presets": ["@babel/preset-env"]
}
包.json
{
"name": "elinodereactapp",
"version": "1.0.0",
"description": "",
"scripts": {
"start": "nodemon --exec babel-node ./app.js",
"test": "mocha --require @babel/register tests/*.js --exit",
"build": "babel src --out-dir ./dist --source-maps",
"serve": "node ./app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"assert": "^1.4.1",
"body-parser": "^1.18.3",
"chai-http": "^4.2.1",
"cookie-parser": "^1.4.4",
"cors": "^2.8.5",
"dotenv": "^7.0.0",
"express": "^4.16.4",
"morgan": "^1.9.1",
"node-mocks-http": "^1.7.3"
},
"devDependencies": {
"@babel/cli": "^7.4.3",
"@babel/core": "^7.4.3",
"@babel/node": "^7.2.2",
"@babel/preset-env": "^7.4.3",
"@babel/register": "^7.4.0",
"babel-cli": "^6.26.0",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "^8.0.5",
"babel-preset-env": "^1.7.0",
"chai": "^4.2.0",
"mocha": "^6.1.1",
"nodemon": "^1.18.10"
}
}
解决方案
你需要使用res.body.message
而不是res.message
describe('index page should render, hello world', () => {
it('should render hello world 200', (done) => {
chai.request(router).get('/').then((res)=>{
expect(res.body.message).to.equal("Hello World");
expect(res).to.have.status(200);
done();
})
})
})
推荐阅读
- javascript - 重绘和重排的这个函数在做什么?
- c# - Xamarin.android Microsoft.SQLite 始终不返回任何行
- flutter - 在 Flutter 中,是否可以将我的 MaterialApp 的 themeData 设置为使用大写作为所有文本值的默认值?
- python - 如何从字典创建df,其中一个字典的值在另一个字典中
- java - 我缺少哪些元素来确保 mailR 通过数据服务器与 Java 集成顺利运行?
- java - Spring Boot:自定义 AutoConfiguration 类找不到属性
- postgresql - docker-compose 启动时如何创建数据库表并在 postgres DB 中插入数据
- arrays - 从 Flutter 中嵌套映射对象的复杂列表访问变量值
- spring-boot - 使用 Dockerfile 为 Spring Boot jar 指示应用程序属性时没有此类文件
- objective-c - 从 macOS 应用程序以编程方式使用 Spotlight 时,如何搜索网络卷?