これはおそらく非同期コードに関係していますが、何が原因かはわかりません。両方を別々に実行すると、両方が合格しますmocha test/models.coffee
。mocha test/login.coffee
しかしdescribe 'saving another user with same username', ->
、一緒にテストを実行すると失敗しますnpm test
。そのステップを実行しているときにデータベースがクリアされ、エラーが発生する代わりに保存されると思います。これは、一意の値であるはずだからです。
また、私はこのソフトウェアのテストに関して非常に新しいものです。誰かが何かヒントを持っている場合、または私の露骨な間違いを批判したい場合は、お気軽に私にメールしてください (プロフィールを確認してください)。
ありがとう!!
ここに私の2つのテストファイル(coffeescript)があります:
/test/models.coffee
should = require 'should'
{User} = require '../models'
# function to find our test user, John Egbert
findJohn = (cb) ->
User.findOne {'public.username': 'john'}, (err, john) ->
throw err if err
cb(john)
before (done) ->
# Drop all users from database
User.collection.drop()
# Create our test user, his username is John Egbert
User.create
password: 'test123'
public: {username: 'john'}, done
describe 'create user', ->
it 'should create a document that can be found', (done) ->
findJohn (user) ->
should.exist user
done()
describe 'user password', ->
it 'should NOT be stored in plaintext', (done) ->
findJohn (user) ->
user.password.should.not.eql 'test123'
done()
it 'should return true for matching password', (done) ->
findJohn (user) ->
user.comparePassword 'test123', (err, isMatch) ->
isMatch.should.eql true
done()
it 'should return false for non-matching password', (done) ->
findJohn (user) ->
user.comparePassword 'wrong_password', (err, isMatch) ->
isMatch.should.not.eql true
done()
describe 'saving another user with same username', ->
it 'should produce an error', (done) ->
User.create public: {username: 'john'}, (err) ->
should.exist err
done()
/test/login.coffee
:
should = require 'should'
{User} = require '../models'
login = require '../services/login'
before (done) ->
# Drop all users from database
User.collection.drop()
# Create our test user, his username is John Egbert
User.create
password: 'test123'
public: {username: 'john'}, done
describe 'login', ->
it 'should return true for an existing username/password combo', (done) ->
login username: 'john', password: 'test123', (err, loggedIn) ->
should.not.exist(err)
loggedIn.should.be.true
done()
it 'should return false for a bad username/password combo', (done) ->
login username: 'john', password: 'wrong_pass', (err, loggedIn) ->
should.not.exist(err)
loggedIn.should.be.false
done()
と/models.coffee
fs = require 'fs'
path = require 'path'
mongoose = require 'mongoose'
#Connect to mongodb
#TODO: env variable to choose production/development/testing databases
mongoose.connect 'localhost', 'siglr'
models = {}
for file in fs.readdirSync './schemas'
if path.extname(file) is '.coffee'
modelName = path.basename file, '.coffee'
schema = require "./schemas/#{modelName}"
models[modelName] = mongoose.model modelName, schema
# key is model name, value is actual mongoose model
module.exports = models