简体   繁体   English

使用Mocha和Supertest进行NodeJS单元测试-“ assert”似乎没有按预期工作?

[英]NodeJS unit testing with Mocha and Supertest - `assert` does not seem working as expected?

assert does not seem working as expected. assert似乎没有按预期工作。

This is my package.json: 这是我的package.json:

"devDependencies": {
    "babel-eslint": "^7.2.3",
    "backpack-core": "^0.4.1",
    "mocha": "^3.5.0",
    "supertest": "^3.0.0"
  },
  "scripts": {
    "test": "NODE_PATH=./server:./server/modules mocha ./test/*.js --compilers js:babel-core/register --recursive",
    "dev": "backpack dev",
    "build": "nuxt build && backpack build",
    "start": "cross-env NODE_ENV=production node build/main.js"
  },

My test: 我的测试:

'use strict'

import app from '../server/index'
import supertest from 'supertest'
import assert from 'assert'

const request = supertest.agent(app)

var _id
var name
describe('POST /api/users with data', function () {
  it('status code should be 200', function (done) {
    request
      .post('/api/users')
      .type('form')
      .send({name: 'tom'})
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
        console.log(res.body)
        if (err) return done(err)

        name = res.body.ops[0].name.toString()
        _id = res.body.ops[0]._id.toString()
        console.log(name)

        assert(name, 'tomx') // should not pass this.

        done()
      })
  })
})

Result: 结果:

  POST /api/users with data
{ result: { ok: 1, n: 1 },
  ops: [ { id: 'xxx', name: 'tom', _id: '59a7c33ba17bd32431c4134b' } ],
  insertedCount: 1,
  insertedIds: [ '59a7c33ba17bd32431c4134b' ] }
tom
    ✓ status code should be 200 (54ms)

At assert(name, 'tomx') - Why is passed? assert(name, 'tomx') -为什么通过? It is tom that should be passed. 它应该是tom

Any ideas? 有任何想法吗?

assert is just a shorthand for assert.ok which validates that the first argument is truthy https://nodejs.org/api/assert.html#assert_assert_value_message assert只是assert.ok的简写assert.ok ,它验证第一个参数是否为真https://nodejs.org/api/assert.html#assert_assert_value_message

You should use assert.equal or assert.strictEqual instead. 您应该改用assert.equalassert.strictEqual Another option is modifying your assertion: 另一个选择是修改您的断言:

assert(name === 'tomx')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM