thinkjs / thinkjs

Use full ES2015+ features to develop Node.js applications, Support TypeScript.
https://thinkjs.org/
MIT License
5.31k stars 616 forks source link

[利用Mocha测试]如何用Mocha对ThinkJS 3.0进行单元测试 #841

Closed wurining closed 7 years ago

wurining commented 7 years ago

DESC

在Thinkjs项目中引入了Mocha进行单元测试。例如对Model的某个方法进行测试,但是启动后提示think is not defined。全部错误如下:

(function (exports, require, module, __filename, __dirname) { module.exports = class extends think.Model {
                                                                                             ^

ReferenceError: think is not defined
    at Object.<anonymous> (/***/WebStormPRO/work-day/src/model/record.js:1:94)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/***/WebStormPRO/work-day/test/model.test.js:5:19)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at /***/WebStormPRO/work-day/node_modules/mocha/lib/mocha.js:231:27
    at Array.forEach (native)
    at Mocha.loadFiles (/***/WebStormPRO/work-day/node_modules/mocha/lib/mocha.js:228:14)
    at Mocha.run (/***/WebStormPRO/work-day/node_modules/mocha/lib/mocha.js:514:10)
    at Object.<anonymous> (/***/WebStormPRO/work-day/node_modules/mocha/bin/_mocha:480:18)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3

ENV

Platform: Mac OS 10.12.3 Node.js Version: 8.2.1 ThinkJS Version: 3.0.0

welefen commented 7 years ago

需要引入 think 模块,这块还有些问题,我们处理下这个。

welefen commented 7 years ago

ThinkJS 3.2.1 版本已经解决这个问题,需要添加的配置:

1、在 package.json 中追加下面的配置:

"scripts": {
    "test": "THINK_UNIT_TEST=1 nyc ava test/ && nyc report --reporter=html"
  },
  "devDependencies": {
    "ava": "^0.18.0",
    "nyc": "^7.0.0"
  },

执行 npm install,安装新的依赖。

2、修改测试文件 test/xxx.js,引入对应的文件:

const path = require('path');
require(path.join(process.cwd(), 'production.js'));

完整的例子为:

const test = require('ava');
const path = require('path');
require(path.join(process.cwd(), 'production.js'));

test('eee', t => {
  const a = think.model('a');
  console.log(a.test())
})

后续 think-cli 版本里会自动创建这些代码。

wurining commented 7 years ago

@welefen 非常感谢!已经搞定,非常棒!而且还知道两个好用的新工具,另外李老师,您博客归档栏目下的部分文章无法访问,出现500错误: )

matinjugou commented 6 years ago

追加这些配置后显示'THINK_UNIT_TEST' 不是内部或外部命令,也不是可运行的程序

lizheming commented 6 years ago

Windows 需要使用 set THINK_UNIT_TEST = true 来赋值。

matinjugou commented 6 years ago

谢谢!

matinjugou commented 6 years ago

为什么会出现require development环境抛出错误的问题? test/index.js

const test = require('ava');
const path = require('path');
require(path.join(process.cwd(), 'development.js'));

test('eee', t => {
  t.pass();
});

./development.js

const Application = require('thinkjs');
const babel = require('think-babel');
const watcher = require('think-watcher');
const notifier = require('node-notifier');

const instance = new Application({
  ROOT_PATH: __dirname,
  watcher: watcher,
  transpiler: [babel, {
    presets: ['think-node']
  }],
  notifier: notifier.notify.bind(notifier),
  env: 'development'
});

instance.run();

D:\Files\清华大学\大三\软件工程3\yogurt-backend>npm run test

> thinkjs-application@1.0.0 test D:\Files\清华大学\大三\软件工程3\yogurt-backend
> ava test/
{ NotFoundError: url `%7B%22file%22:%22D://Files//清华大学//大三//软件工程3//yogurt-backend//test//index.js%22,%22baseDir%22
:%22D://Files//清华大学//大三//软件工程3//yogurt-backend%22,%22tty%22:%7B%22columns%22:124,%22rows%22:27%7D,%22match%22:[],%
22failFast%22:false,%22serial%22:false,%22require%22:[],%22cacheEnabled%22:true,%22powerAssert%22:true,%22explicitTitles%22:
false,%22babelConfig%22:%22default%22,%22resolveTestsFrom%22:%22D://Files//清华大学//大三//软件工程3//yogurt-backend%22,%22p
rojectDir%22:%22D://Files//清华大学//大三//软件工程3//yogurt-backend%22,%22concurrency%22:0,%22updateSnapshots%22:false,%22c
olor%22:true,%22cacheDir%22:%22D://Files//清华大学//大三//软件工程3//yogurt-backend//node_modules//.cache//ava%22,%22precomp
iled%22:%7B%22D://Files//清华大学//大三//软件工程3//yogurt-backend//test//index.js%22:%22f948fdaa843f7a4fa42e4e500ece23d5%22
%7D%7D` not found.
    at Object.throw (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_koa@2.4.1@koa\lib\context.js:92:11)
    at beforeTrace.then.then (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_think-trace@1.0.13@think-trace\l
ib\index.js:33:23)
    at tryCatcher (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js\release\util.js:
16:23)
    at Promise._settlePromiseFromHandler (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@blueb
ird\js\release\promise.js:502:31)
    at Promise._settlePromise (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js\rele
ase\promise.js:559:18)
    at Promise._settlePromise0 (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js\rel
ease\promise.js:604:10)
    at Promise._settlePromises (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js\rel
ease\promise.js:683:18)
    at Async._drainQueue (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js\release\a
sync.js:138:16)
    at Async._drainQueues (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js\release\
async.js:148:10)
    at Immediate.Async.drainQueues (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js
\release\async.js:17:14)
    at runCallback (timers.js:789:20)
    at tryOnImmediate (timers.js:751:5)
    at processImmediate [as _immediateCallback] (timers.js:722:5)
  message: 'url `%7B%22file%22:%22D://Files//清华大学//大三//软件工程3//yogurt-backend//test//index.js%22,%22baseDir%22:%22D
://Files//清华大学//大三//软件工程3//yogurt-backend%22,%22tty%22:%7B%22columns%22:124,%22rows%22:27%7D,%22match%22:[],%22fai
lFast%22:false,%22serial%22:false,%22require%22:[],%22cacheEnabled%22:true,%22powerAssert%22:true,%22explicitTitles%22:false
,%22babelConfig%22:%22default%22,%22resolveTestsFrom%22:%22D://Files//清华大学//大三//软件工程3//yogurt-backend%22,%22projec
tDir%22:%22D://Files//清华大学//大三//软件工程3//yogurt-backend%22,%22concurrency%22:0,%22updateSnapshots%22:false,%22color%
22:true,%22cacheDir%22:%22D://Files//清华大学//大三//软件工程3//yogurt-backend//node_modules//.cache//ava%22,%22precompiled%
22:%7B%22D://Files//清华大学//大三//软件工程3//yogurt-backend//test//index.js%22:%22f948fdaa843f7a4fa42e4e500ece23d5%22%7D%7
D` not found.' } { request:
   { method: 'CLI',
     url: '{"file":"D:\\\\Files\\\\清华大学\\\\大三\\\\软件工程3\\\\yogurt-backend\\\\test\\\\index.js","baseDir":"D:\\\\Fil
es\\\\清华大学\\\\大三\\\\软件工程3\\\\yogurt-backend","tty":{"columns":124,"rows":27},"match":[],"failFast":false,"serial":
false,"require":[],"cacheEnabled":true,"powerAssert":true,"explicitTitles":false,"babelConfig":"default","resolveTestsFrom":
"D:\\\\Files\\\\清华大学\\\\大三\\\\软件工程3\\\\yogurt-backend","projectDir":"D:\\\\Files\\\\清华大学\\\\大三\\\\软件工程3\
\\\yogurt-backend","concurrency":0,"updateSnapshots":false,"color":true,"cacheDir":"D:\\\\Files\\\\清华大学\\\\大三\\\\软件
工程3\\\\yogurt-backend\\\\node_modules\\\\.cache\\\\ava","precompiled":{"D:\\\\Files\\\\清华大学\\\\大三\\\\软件工程3\\\\yo
gurt-backend\\\\test\\\\index.js":"f948fdaa843f7a4fa42e4e500ece23d5"}}',
     header: {} },
  response:
   { status: 404,
     message: 'Not Found',
     header: { 'x-powered-by': 'thinkjs-3.2.4', vary: 'Origin' } },
  app: { subdomainOffset: 2, proxy: false, env: 'development' },
  originalUrl: '{"file":"D:\\\\Files\\\\清华大学\\\\大三\\\\软件工程3\\\\yogurt-backend\\\\test\\\\index.js","baseDir":"D:\\
\\Files\\\\清华大学\\\\大三\\\\软件工程3\\\\yogurt-backend","tty":{"columns":124,"rows":27},"match":[],"failFast":false,"ser
ial":false,"require":[],"cacheEnabled":true,"powerAssert":true,"explicitTitles":false,"babelConfig":"default","resolveTestsF
rom":"D:\\\\Files\\\\清华大学\\\\大三\\\\软件工程3\\\\yogurt-backend","projectDir":"D:\\\\Files\\\\清华大学\\\\大三\\\\软件
工程3\\\\yogurt-backend","concurrency":0,"updateSnapshots":false,"color":true,"cacheDir":"D:\\\\Files\\\\清华大学\\\\大三\\\
\软件工程3\\\\yogurt-backend\\\\node_modules\\\\.cache\\\\ava","precompiled":{"D:\\\\Files\\\\清华大学\\\\大三\\\\软件工程3\
\\\yogurt-backend\\\\test\\\\index.js":"f948fdaa843f7a4fa42e4e500ece23d5"}}',
  req: '<original node req>',
  res: '<original node res>',
  socket: '<original node socket>' }

  TypeError: Cannot read property 'replace' of undefined
      at Tracer.renderNotFound (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_think-trace@1.0.13@think-trace
\lib\tracer.js:106:32)
      at Tracer.run (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_think-trace@1.0.13@think-trace\lib\tracer
.js:131:23)
      at beforeTrace.then.then.catch.err (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_think-trace@1.0.13@t
hink-trace\lib\index.js:47:21)
      at tryCatcher (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js\release\util.j
s:16:23)
      at Promise._settlePromiseFromHandler (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@blu
ebird\js\release\promise.js:502:31)
      at Promise._settlePromise (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js\re
lease\promise.js:559:18)
      at Promise._settlePromise0 (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js\r
elease\promise.js:604:10)
      at Promise._settlePromises (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js\r
elease\promise.js:679:18)
      at Async._drainQueue (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js\release
\async.js:138:16)
      at Async._drainQueues (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\js\releas
e\async.js:148:10)
      at Immediate.Async.drainQueues (D:\Files\清华大学\大三\软件工程3\yogurt-backend\node_modules\_bluebird@3.3.5@bluebird\
js\release\async.js:17:14)
      at runCallback (timers.js:789:20)
      at tryOnImmediate (timers.js:751:5)
      at processImmediate [as _immediateCallback] (timers.js:722:5)

  1 exception

  × Test results were not received from test\index.js

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! thinkjs-application@1.0.0 test: `ava test/`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the thinkjs-application@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     D:\SoftWares\nodejs\node_cache\_logs\2017-12-06T02_54_01_077Z-debug.log

thinkjs: version 3.2.4 npm: version 5.5.1 nodejs: version 8.9.0

welefen commented 6 years ago

@matinjugou

require(path.join(process.cwd(), 'development.js')); 这里用 production.js。

另外有配置 set THINK_UNIT_TEST = true 么?

matinjugou commented 6 years ago

解决了,问题是在于必须把set THINK_UNIT_TEST = true写到script里,不能先执行它再npm run test……, 还有一个问题,就是这种方式是把think的环境注入到测试文件全局,但是像

const test = require('ava');
const request = require('supertest');
const path = require('path');
const chai = require('chai');
const should = chai.should();
const assert = chai.assert;
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
const sinon = require('sinon');
const Q = require('q');
/*
const Application = require('thinkjs');
function createServer() {
  const instance = new Application({
    ROOT_PATH: __dirname,
    proxy: true, // use proxy
    env: 'production'
  });

  return instance.run();
}
*/
require(path.join(process.cwd(), 'production.js'));

test.cb('postAction', t => {
  const body = {
    staffId: '1_s1',
    password: '1_s1'
  };
  const staff = think.model('staff');
  const stub =  sinon.stub(staff, "validateStaff");
  function staffValidatePromise() {
    return Q.fcall(function() {
      return {
        staffId: '1_s1',
        companyId: 1,
        isInit: true,
        status: 1
      };
    });
  }
  stub.withArgs('1_s1', '1_s1').returns(staffValidatePromise());
  request(process.cwd())  //这里应该怎么处理?
    .post('/api/staff/login')
    .set('Content-Type', 'multipart/form-data')
    .field('raw', JSON.stringify(body))
    .end(function (err, res) {
      if (err) {
        console.log(err);
      }
      if (res) {
        console.log(res);
      }
      done();
    })
  t.pass();
});

这样的代码里,试图mock model并通过fetch或者supertest这样的库去测试controller的业务逻辑的话,fetch(‘xxx’)或者supertest的request('xxxx')这个app.address该写什么呢?

matinjugou commented 6 years ago

这样的写法在做travis自动化测试的时候会出现这样的报错:

$ npm run test
> thinkjs-application@1.0.0 test /home/travis/build/matinjugou/yogurt-backend
> THINK_UNIT_TEST=1 nyc ava test/ && nyc report --reporter=html
(node:4572) Warning: process.on(SIGPROF) is reserved while debugging
failed to instrument /home/travis/build/matinjugou/yogurt-backend/src/model/manager.js with error: Unexpected token (17:8)
failed to instrument /home/travis/build/matinjugou/yogurt-backend/src/model/note.js with error: Unexpected token (14:8)
failed to instrument /home/travis/build/matinjugou/yogurt-backend/src/model/quickReplyPublic.js with error: Unexpected token (22:8)
failed to instrument /home/travis/build/matinjugou/yogurt-backend/src/model/sessionPair.js with error: Unexpected token (15:8)
failed to instrument /home/travis/build/matinjugou/yogurt-backend/src/model/staff.js with error: Unexpected token (2:8)
failed to instrument /home/travis/build/matinjugou/yogurt-backend/src/model/user.js with error: Unexpected token (6:8)
{ Error: Cannot find module '../../base.js'
    at Function.Module._resolveFilename (module.js:555:15)
    at Function.Module._load (module.js:482:25)
    at Module.require (module.js:604:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/travis/build/matinjugou/yogurt-backend/src/logic/api/manager/user/list.js:1:999)
    at Module._compile (module.js:660:30)
    at Module.replacementCompile (/home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:63:13)
    at module.exports (/home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/default-require-extensions/js.js:8:9)
    at /home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:67:4
    at extensions.(anonymous function) (/home/travis/build/matinjugou/yogurt-backend/node_modules/require-precompiled/index.js:16:3)
    at /home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:67:4
    at require.extensions.(anonymous function) (/home/travis/build/matinjugou/yogurt-backend/node_modules/ava/lib/process-adapter.js:105:4)
    at Object.<anonymous> (/home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:67:4)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Module.require (module.js:604:17)
    at require (internal/module.js:11:18)
    at exports.interopRequire (/home/travis/build/matinjugou/yogurt-backend/node_modules/think-loader/loader/util.js:14:13)
    at files.forEach.file (/home/travis/build/matinjugou/yogurt-backend/node_modules/think-loader/loader/common.js:16:26)
    at Array.forEach (<anonymous>)
    at Object.loadFiles (/home/travis/build/matinjugou/yogurt-backend/node_modules/think-loader/loader/common.js:12:11)
    at Object.load (/home/travis/build/matinjugou/yogurt-backend/node_modules/think-loader/loader/common.js:64:32)
    at Loader.loadLogic (/home/travis/build/matinjugou/yogurt-backend/node_modules/think-loader/index.js:55:19)
    at thinkLoader.loadData (/home/travis/build/matinjugou/yogurt-backend/node_modules/thinkjs/lib/loader.js:44:37)
    at thinkLoader.loadAll (/home/travis/build/matinjugou/yogurt-backend/node_modules/thinkjs/lib/loader.js:110:12)
    at Application.run (/home/travis/build/matinjugou/yogurt-backend/node_modules/thinkjs/lib/application.js:196:18)
    at Object.<anonymous> (/home/travis/build/matinjugou/yogurt-backend/production.js:2:73)
    at Module._compile (module.js:660:30)
    at Module.replacementCompile (/home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:63:13)
    at module.exports (/home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/default-require-extensions/js.js:8:9)
    at /home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:67:4
    at extensions.(anonymous function) (/home/travis/build/matinjugou/yogurt-backend/node_modules/require-precompiled/index.js:16:3)
    at /home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:67:4
    at require.extensions.(anonymous function) (/home/travis/build/matinjugou/yogurt-backend/node_modules/ava/lib/process-adapter.js:105:4)
    at Object.<anonymous> (/home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:67:4)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Module.require (module.js:604:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/travis/build/matinjugou/yogurt-backend/test/controller.api.staff.login.js:4:1)
    at Module._compile (module.js:660:30)
    at Module.replacementCompile (/home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:63:13)
    at extensions.(anonymous function) (/home/travis/build/matinjugou/yogurt-backend/node_modules/require-precompiled/index.js:13:11)
    at /home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:67:4
    at require.extensions.(anonymous function) (/home/travis/build/matinjugou/yogurt-backend/node_modules/ava/lib/process-adapter.js:105:4)
    at Object.<anonymous> (/home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:67:4)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Module.require (module.js:604:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/travis/build/matinjugou/yogurt-backend/node_modules/ava/lib/test-worker.js:33:1)
    at Module._compile (module.js:660:30)
    at Module.replacementCompile (/home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:63:13)
    at module.exports (/home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/default-require-extensions/js.js:8:9)
    at Object.<anonymous> (/home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/node_modules/append-transform/index.js:67:4)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Function.Module.runMain (module.js:701:10)
    at Function.runMain (/home/travis/.node-spawn-wrap-4572-6a0126b6422e/node:40:10)
    at Object.<anonymous> (/home/travis/build/matinjugou/yogurt-backend/node_modules/nyc/bin/wrap.js:20:4)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Function.Module.runMain (module.js:701:10)
    at Object.<anonymous> (/home/travis/.node-spawn-wrap-4572-6a0126b6422e/node:140:8)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Function.Module.runMain (module.js:701:10)
    at startup (bootstrap_node.js:194:16)
    at bootstrap_node.js:618:3 code: 'MODULE_NOT_FOUND' }
server= undefined

我尝试这样打印了think.app.server结果发现时undefined,因此也就无法用supertest通过request(think.app.server)的方式发起请求,代码如下:

const test = require('ava');
const request = require('supertest');
const path = require('path');
require(path.join(process.cwd(), 'production.js'));

test('eee', t => {
  console.error("server=", think.app.server);
  /*
  request(think.app.server).post('/api/staff/login')
    .set('Content-Type', 'application/json')
    .send({
      staffId: '1_s1',
      password: '1_s2'
    })
    .expect('Content-Type', /json/)
    .expect(200);
  */
  const a = think.model('staff');
  console.error(a);
  t.pass();
});

travis.yml:

sudo: false
language: node_js
node_js:
  - node
services:
  - mongodb
  - redis-server
  - mysql
before_install:
  - mysql -e 'CREATE DATABASE yogurt_test CHARACTER SET utf8 COLLATE utf8_unicode_ci;'
  - mysql -e 'CREATE TABLE yogurt_test.staff
             (
               staffId      VARCHAR(45)  NOT NULL,
               companyId    INT UNSIGNED NULL,
               isInit       TINYINT      NULL,
               name         VARCHAR(45)  NULL,
               email        VARCHAR(45)  NULL,
               tel          VARCHAR(45)  NULL,
               nickname     VARCHAR(45)  NULL,
               password     VARCHAR(45)  NULL,
               picUrl       VARCHAR(200) NULL,
               role         VARCHAR(45)  NULL,
               onlineStatus TINYINT      NULL,
               servingCount INT UNSIGNED NULL,
               waitingCount INT UNSIGNED NULL,
               queueCount   INT UNSIGNED NULL,
               id           INT UNSIGNED AUTO_INCREMENT
                 PRIMARY KEY,
               AnsAsk       VARCHAR(200) NULL,
               CONSTRAINT id_UNIQUE
               UNIQUE (staffId)
             )
               ENGINE = InnoDB;'
cache:
  directories:
    - node_modules
before_script:
  - npm prune
script:
  - npm run lint
  - npm run test

这是为什么 thinke.model('staff')打印的结果如下:

Model {
  config: 
   { logConnect: false,
     logSql: false,
     logger: [Function: logger],
     handle: 
      { [Function: Mysql]
        Query: [Function: MysqlQuery],
        Schema: [Function: MysqlSchema],
        Parser: [Function: MysqlParser] },
     database: '',
     prefix: 'think_',
     encoding: 'utf8',
     host: '127.0.0.1',
     port: '',
     user: 'root',
     password: 'root',
     dateStrings: true,
     type: 'mysql' },
  modelName: 'staff',
  options: {},
  _cacheConfig: 
   { type: 'redis',
     file: 
      { timeout: 86400000,
        handle: [Function: FileCache],
        cachePath: '/home/travis/build/matinjugou/yogurt-backend/runtime/cache',
        pathDepth: 1,
        gcInterval: 86400000 },
     redis: 
      { timeout: 86400000,
        handle: [Function: RedisCache],
        port: 6379,
        host: '123.206.22.71',
        password: '' } },
  [Symbol(think-model-relation)]: Relation { model: [Circular], relation: {}, relationName: true },
  [Symbol(think-models)]: 
   { user: [Function: Model],
     staff: [Function: Model],
     sessionPair: [Function: Mongo],
     quickReplyPublic: [Function: Mongo],
     quickReplyPrivate: [Function: Mongo],
     note: [Function: Model],
     manager: [Function: Model],
     index: [Function: Model],
     company: [Function: Model],
     comments: [Function: Model] } }
tempest2023 commented 5 years ago

Hello, I change the package.json and test.js as you said. The version of my thinkjs is 3.2.10. I found I must run the tests as "THINK_UNIT_TEST=1 ava test/" otherwise I can not get the variable think.

When I run npm test, there is an error about nyc which is failed to instrument xxx.js with error: Unexpected token. It seems like nyc can not understand async xxxAction(){}, but xxxAction(){} can work.

The code of my index.js

async registryAction() {
    let postdata = this.post();
    let phone = postdata["phone"];
}

Any ideas?

lizheming commented 5 years ago

@623059088 try to upgrade Node.js version to 8.9.4+

tempest2023 commented 5 years ago

Thank you but the version of my Node.js is 10.12.0. And it still does not work.

lizheming commented 5 years ago

@623059008 then try to upgrade nyc to latest version (right now it's 14.0.0).

tempest2023 commented 5 years ago

I'm still confused by it. My version is latest.

lizheming commented 5 years ago

@623059008 You should get nyc version by npm list nyc, it's global nyc module version you showed in screenshot.

tempest2023 commented 5 years ago

Thank you. It totally solve my problem.