Skip to content

Commit

Permalink
Added tests for this.file, related to #50
Browse files Browse the repository at this point in the history
  • Loading branch information
lazd committed Jun 20, 2017
1 parent aeeda61 commit cfc25b8
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
9 changes: 4 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,17 @@ var Transform = require('readable-stream/transform');
var rs = require('replacestream');
var istextorbinary = require('istextorbinary');

module.exports = function(search, replacement_, options) {
module.exports = function(search, replacement, options) {
return new Transform({
objectMode: true,
transform: function(file, enc, callback) {
if (file.isNull()) {
return callback(null, file);
}

if (typeof replacement_ === 'function') {
var replacement = replacement_.bind({file:file});
}else{
var replacement = replacement_;
if (typeof replacement === 'function') {
// Pass the vinyl file object as this.file
replacement = replacement.bind({ file: file });
}

function doReplace() {
Expand Down
4 changes: 4 additions & 0 deletions test/expected/hellofilename.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Hello old helloworld.txt!
Hello new helloworld.txt!
Hello kind helloworld.txt!
Hello cruel helloworld.txt!
30 changes: 30 additions & 0 deletions test/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ describe('gulp-replace', function() {

beforeEach(function () {
file = new File({
base: 'test/fixtures/',
path: 'test/fixtures/helloworld.txt',
contents: fs.createReadStream('test/fixtures/helloworld.txt')
});
Expand All @@ -123,6 +124,35 @@ describe('gulp-replace', function() {
};
});

it('should have this.file set to the vinyl file object', function(done) {
var stream = replacePlugin('world', function() {
this.file.should.equal(file);
return 'person';
});
check(stream, done, function (data) {
data.should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
});
});

it('should have this.file set to the vinyl file object for regex replaces', function(done) {
var stream = replacePlugin(/world/g, function() {
this.file.should.equal(file);
return 'person';
});
check(stream, done, function (data) {
data.should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
});
});

it('should replace filenames', function(done) {
var stream = replacePlugin('world', function() {
return this.file.relative;
});
check(stream, done, function (data) {
data.should.equal(fs.readFileSync('test/expected/hellofilename.txt', 'utf8'));
});
});

it('should replace string on a stream', function(done) {
var stream = replacePlugin('world', 'person');
check(stream, done, function (data) {
Expand Down

0 comments on commit cfc25b8

Please sign in to comment.