首页 > 解决方案 > 在 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"
  }
}

标签: javascriptexpressmocha.jschai

解决方案


你需要使用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();
            })
    })    
})

推荐阅读