我有一个非常简单的 yeoman 生成器,watchjs
,它有 speaker
子发电机。下面是它的使用方法:
$哟watchjs:扬声器
你调用了 watch.js 扬声器子生成器。
?演讲者文件:data/speakers/speakers.json
?演讲者姓名:abc
{ 文件:'data/speakers/speakers.json',名称:'abc' }
生成的 slug 是:abc
试图添加:{
"id": "abc",
“姓名”:“abc”
}
主要有两个提示:file
- 定义数据应附加到的 json 文件和 name
- 定义要添加到文件中的实际数据(稍作修改)。我正在尝试为此编写一个简单的 yeoman 测试。我一直在努力关注 the docs ,但我一直都在失败:
$ npm test
> generator-watchjs@0.0.2 test c:\Users\tomasz.ducin\Documents\GitHub\generator-watchjs
> mocha
Watchjs:speaker
{ file: 'speakers.json', name: 'John Doe' } // <- this is my console.log
1) "before all" hook
0 passing (59ms)
1 failing
1) Watchjs:speaker "before all" hook:
Uncaught Error: ENOENT, no such file or directory 'C:\Users\TOMASZ~1.DUC\AppData\Local\Temp\53dac48785ddecb6dabba402eeb04f91e322f844\speakers.json'
at Object.fs.openSync (fs.js:439:18)
at Object.fs.readFileSync (fs.js:290:15)
at module.exports.yeoman.generators.Base.extend.writing (c:\Users\tomasz.ducin\Documents\GitHub\generator-watchjs\speaker\index.js:43:33)
npm ERR! Test failed. See above for more details.
我不明白文件实际创建在哪里以及测试在哪里寻找它...似乎使用了一个临时的 Windows 位置,但无论如何,如果所有事情相对于路径正常工作,文件应该已经找到了,但没有。无法弄清楚如何使测试通过。
我的测试文件最好的内容是:
'use strict';
var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
describe('watchjs:speaker', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../speaker'))
.withOptions({ 'skip-install': true })
.withPrompts({ 'file': 'speakers.json', 'name': "John Doe" })
.on('end', done);
});
it('creates files', function () {
assert.file([
'speakers.json'
]);
});
});
我正在通过提示传递特定的 name
和 file
名称。
我发现 npm test
调用了 package.json 的 mocha
命令(仅此而已)。但我不是 Mocha 专家。
我在 Windows7 上使用 Node v0.10.35。
最佳答案
首先,您应该在测试中使用绝对路径,这样文件的位置是可预测的。
我的测试看起来像这样:
'use strict';
var fs = require('fs');
var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
describe('watchjs:speaker', function () {
before(function (done) {
var self = this;
var name = 'John Doe';
var testPath = path.join(__dirname, 'temp');
// store in test obejct for later use
this.filePath = path.join(testPath, 'speaker.json');
helpers.run(path.join(__dirname, '../speaker'))
.inDir(testPath)
.withPrompts({ 'file': self.filePath, 'name': name })
.withOptions({ 'skip-install': true })
.on('end', done);
});
it('creates files', function () {
assert.file(this.filePath);
assert.fileContent(this.filePath, /\"id\":.*\"john-doe\"/);
assert.fileContent(this.filePath, /\"name\":.*\"John Doe\"/);
});
});
其次,与您的问题没有直接关系,上面的测试将针对您共享的存储库中的代码进行。就像我在评论中提到的那样,它会引发错误 here如果该文件尚不存在。
我会改变:
var content = JSON.parse(fs.readFileSync(this.options.file, 'utf8'));
到:
try {
var content = JSON.parse(fs.readFileSync(this.options.file, 'utf8'));
} catch(e) {
content = [];
}
通过上述更改,测试将通过。
关于javascript - 自定义 yeoman 生成器测试 : creating files,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30694802/