首页 > 解决方案 > Chai 单元测试意外的令牌 { 在 JSON 中的位置 25

问题描述

试图测试一个休息端点,但我得到了

索引页面应该呈现,你好世界

应该呈现 hello world 200:

 SyntaxError: Unexpected token { in JSON at position 25

不知道我做错了什么。

参考这个

https://github.com/chaijs/chai

router.spec.js

import chai from 'chai';
import { expect } from 'chai';
import chaiHttp from 'chai-http';
import { assert } from 'assert'
import router from '../routes/';

chai.use(chaiHttp);


// simple test
// describe('Array', () => {
//       it('should return -1 when the value is not present', () => {
//         assert.equal([1, 2, 3].indexOf(4), -1);
//       });
// });



describe('index page should render, hello world', () => {
it('should render hello world 200', () => {     
  return chai.request(router)
   .get('/')
   .end((err, res) => {
        res.should.have.status(200);
        res.body.should.be.a('object');
        res.body.length.should.be.eql(0);
     done();
   });
 });   
})

index.js

import express from 'express';

const app = express();

app.get('/', (req, res) => {
   return res.status(200).json({
        message: "Hello World"
    })
})

export default app;

标签: javascriptexpressmocha.jschai

解决方案


我决定采取不同的方法并使用超测。他们是 chai 读取 json 对象的问题。

import chai from 'chai';
import { expect } from 'chai';
import chaiHttp from 'chai-http';
import { assert } from 'assert'
import router from '../routes/';
import request from 'supertest';

chai.use(chaiHttp);


// simple test
// describe('Array', () => {
//       it('should return -1 when the value is not present', () => {
//         assert.equal([1, 2, 3].indexOf(4), -1);
//       });
// });



describe('index page should render 200 request', () => {
  it('should get index 200', () => {     
    request(router)
      .get('/')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200)
      .end((err, res) => {
        if (err) throw err;
      });
    });  
})

推荐阅读