チュートリアルをhttps://scotch.io/tutorials/test-a-node-restful-api-with-mocha-and-chaiから基本的なAPIテストを行うために使用できるベアボーンserver
とtest
に変更しました。
Mr.Phoenixが言ったように、あなたのhandler
の根っからの砂糖に深入りする必要はありません。ちょうどあなたのエンドポイントにいくつかのデータを渡し、期待どおりの結果をチェックしてください。
index.js
const express = require('express')
const app = express()
app.get('/material',(req, res)=>{
res.json([])
//res.json(['stone', 'wood'])
})
function getUserData(id){
return 42
}
const port = 3031
app.listen(port, function(err){
console.log("Listening on port: " + port)
})
module.exports = app
test.js
process.env.NODE_ENV = 'test'
// const Material = require('./materials') // conroller
const chai = require('chai')
const chaiHttp = require('chai-http')
const server = require('./index')
const should = chai.should()
chai.use(chaiHttp)
describe('/GET material',() => {
it('it should get all the materials', (done)=>{
chai.request(server)
.get('/material')
.end((err, res) => {
res.should.have.status(200)
res.body.should.be.a('array')
res.body.length.should.be.eql(0) // start empty
done()
})
})
})
通常、あなただけのコントローラが含まれています。ここでは
は、あなたがこのテストを行うために使用できる2つのファイルがあります別のテストとスパイ、スタブとモックのものがありますので、コントローラをテストすることができます。 APIテストはあまり複雑ではなく、リクエストに対してリクエストを送信し、結果に対してテストを実行するだけです。テストを書くのに十分な情報を提供する公式のドキュメンテーションを見てください。 – Gntem