How to fix type error while using gulp-filter? - gulp-filter

I am mimicking the code from John Papa's outstanding Pluralsight course on Gulp.
When I use the code as shown in John's course:
.pipe(jsFilter)
.pipe($.uglify())
.pipe(jsFilter.restore())
I get an error on the 3rd line of code:
TypeError: Object #<StreamFilter> has no method 'restore'
When I use the code as shown in the readme from gulp-filter
.pipe(jsFilter)
.pipe($.uglify())
.pipe(jsFilter.restore)
I get an error that it can't pipe to undefined.
Based on what I can find online, both of these patterns are working for others. Any clues as to why this might be happening?
Here is the whole task, if that helps and the console logging indicates that everything if fine until the filter restore call.
Here is the entire task if that helps:
gulp.task('build-dist', ['inject', 'templatecache'], function() {
log('Building the distribution files in the /dist folder');
var assets = $.useref.assets({searchPath: './'});
var templateCache = config.temp + config.templateCache.file;
var jsFilter = $.filter('**/*.js');
return gulp
.src(config.index)
.pipe($.plumber({errorHandler: onError}))
.pipe($.inject(gulp.src(templateCache, {read: false}), {
starttag: '<!-- inject:templates:js -->'
}))
.pipe(assets)
.pipe(jsFilter)
.pipe($.uglify())
.pipe(jsFilter.restore())
.pipe(assets.restore())
.pipe($.useref())
.pipe(gulp.dest(config.dist));
});

The way restore works has changed between the 2.x and 3.x release of gulp-filter.
It seems you're using the 3.x branch, so in order to use restore you'll have to set the restore option to true when defining the filter:
var jsFilter = $.filter('**/*.js', {restore: true});
Then you'll be able to do
.pipe(jsFilter.restore)
For more information, check out this section of the documentation for the latest version of gulp-filter:
https://github.com/sindresorhus/gulp-filter/tree/v3.0.1#restoring-filtered-files

Related

GitHub: How to get `utteranc.es` to work for website discussion

My website https://friendly.github.io/HistDataVis/ wants to use the seemingly light weight and useful discussion feature offered by the https://github.com/utterance app.
I believe I have installed it correctly in my repo, https://github.com/friendly/HistDataVis, but it does not appear on the site when built.
I'm stumped on how to determine what the problem is, or how to correct it. Can anyone help?
For reference, here is my setup:
The website is built in R Studio, using distill in rmarkdown.
I created utterances.html with the standard JS code recommended.
<script>
document.addEventListener("DOMContentLoaded", function () {
if (!/posts/.test(location.pathname)) {
return;
}
var script = document.createElement("script");
script.src = "https://utteranc.es/client.js";
script.setAttribute("repo", "friendly/HistDataVis");
script.setAttribute("issue-term", "og:title");
script.setAttribute("crossorigin", "anonymous");
script.setAttribute("label", "comments ??");
/* wait for article to load, append script to article element */
var observer = new MutationObserver(function (mutations, observer) {
var article = document.querySelector("d-article");
if (article) {
observer.disconnect();
/* HACK: article scroll */
article.setAttribute("style", "overflow-y: hidden");
article.appendChild(script);
}
});
observer.observe(document.body, { childList: true });
});
</script>
In one Rmd file, I use in_header to insert this into the generated HTML file:
---
title: "Discussion"
date: "`r Sys.Date()`"
output:
distill::distill_article:
toc: true
includes:
in_header: utterances.html
---
Also used this in my _site.yml file to apply to all Rmd files on the site.
On my GitHub account, I installed utterances under GitHub apps, and gave it repository access to the repo for this site.
Edit2
Following the solution suggested by #laymonage, I fixed the script. I now get the Comments section on my web page, but get an error, "utterances not installed" when I try to use it. Yet, utterances is installed, as I just checked.
This part of your code:
if (!/posts/.test(location.pathname)) {
return;
}
Prevents the rest of the script to load because it's always true.
The condition checks whether the value of location.pathname passes the regular expression test string posts and negates it (!). That means the condition is true if the location.pathname (the path name of the current URL, e.g. /HistDataVis/ for https://friendly.github.io/HistDataVis/) does not contain posts anywhere in the string. None of the pages on your website has posts in the pathname, so the script will end there.
It should work if you change /posts/ to /HistDataVis or just remove the if block altogether.
Alternatively, you can also try giscus, a similar project that uses GitHub Discussions instead of Issues. Someone already made a guide on how to use it with Distill. Disclaimer: I'm the developer of giscus.

Stop huge error output from testing-library

I love testing-library, have used it a lot in a React project, and I'm trying to use it in an Angular project now - but I've always struggled with the enormous error output, including the HTML text of the render. Not only is this not usually helpful (I couldn't find an element, here's the HTML where it isn't); but it gets truncated, often before the interesting line if you're running in debug mode.
I simply added it as a library alongside the standard Angular Karma+Jasmine setup.
I'm sure you could say the components I'm testing are too large if the HTML output causes my console window to spool for ages, but I have a lot of integration tests in Protractor, and they are SO SLOW :(.
I would say the best solution would be to use the configure method and pass a custom function for getElementError which does what you want.
You can read about configuration here: https://testing-library.com/docs/dom-testing-library/api-configuration
An example of this might look like:
configure({
getElementError: (message: string, container) => {
const error = new Error(message);
error.name = 'TestingLibraryElementError';
error.stack = null;
return error;
},
});
You can then put this in any single test file or use Jest's setupFiles or setupFilesAfterEnv config options to have it run globally.
I am assuming you running jest with rtl in your project.
I personally wouldn't turn it off as it's there to help us, but everyone has a way so if you have your reasons, then fair enough.
1. If you want to disable errors for a specific test, you can mock the console.error.
it('disable error example', () => {
const errorObject = console.error; //store the state of the object
console.error = jest.fn(); // mock the object
// code
//assertion (expect)
console.error = errorObject; // assign it back so you can use it in the next test
});
2. If you want to silence it for all the test, you could use the jest --silent CLI option. Check the docs
The above might even disable the DOM printing that is done by rtl, I am not sure as I haven't tried this, but if you look at the docs I linked, it says
"Prevent tests from printing messages through the console."
Now you almost certainly have everything disabled except the DOM recommendations if the above doesn't work. On that case you might look into react-testing-library's source code and find out what is used for those print statements. Is it a console.log? is it a console.warn? When you got that, just mock it out like option 1 above.
UPDATE
After some digging, I found out that all testing-library DOM printing is built on prettyDOM();
While prettyDOM() can't be disabled you can limit the number of lines to 0, and that would just give you the error message and three dots ... below the message.
Here is an example printout, I messed around with:
TestingLibraryElementError: Unable to find an element with the text: Hello ther. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
...
All you need to do is to pass in an environment variable before executing your test suite, so for example with an npm script it would look like:
DEBUG_PRINT_LIMIT=0 npm run test
Here is the doc
UPDATE 2:
As per the OP's FR on github this can also be achieved without injecting in a global variable to limit the PrettyDOM line output (in case if it's used elsewhere). The getElementError config option need to be changed:
dom-testing-library/src/config.js
// called when getBy* queries fail. (message, container) => Error
getElementError(message, container) {
const error = new Error(
[message, prettyDOM(container)].filter(Boolean).join('\n\n'),
)
error.name = 'TestingLibraryElementError'
return error
},
The callstack can also be removed
You can change how the message is built by setting the DOM testing library message building function with config. In my Angular project I added this to test.js:
configure({
getElementError: (message: string, container) => {
const error = new Error(message);
error.name = 'TestingLibraryElementError';
error.stack = null;
return error;
},
});
This was answered here: https://github.com/testing-library/dom-testing-library/issues/773 by https://github.com/wyze.

SAP UIveri5 Minimum example

I am trying to understand how UIveri5 works and how to apply it to my own projects, but due to the minimal documentation I am unable to create a minimal working example.
I tried to apply the code from https://github.com/SAP/ui5-uiveri5/blob/master/README.md to "my" minimal app ( https://ui5.sap.com/1.62.0/#/sample/sap.m.sample.Button/code/ ), but the IDE VS Code marks errors, since i.e. the commands export or define are not known and I don't see where UIveri5 loads them from. Also if I just execute uiveri5 in my command line as is, I am getting an error ( I guess from selenium ) that my Chrome binary is missing, but don't the drivers get downloaded automatically?
conf.js
exports.config = {
profile: 'integration',
baseUrl: 'localhost:8080/.../sap.m.sample.Button',
};
page.spec.js
describe('Page', function () {
it('should display the page',function() {
element(by.control({
viewName: 'sap.m.sample.Button.Page',
controlType: 'sap.m.Page',
properties: {
title: "Page"
}}));
});
});
It would be awesome if someone already build a minimal example and can share it. It would help me very much in understanding how everything works together.
The minimum example is right in the readme.md. The only problem I see here is with the baseUrl - this should be a valid URL to an existing app. If this is a sample app on your localhost, you need a dev server.

Why do I get "Could not push back" error when trying to use the IBM Bluemix Document Conversion service?

I am trying to convert documents using the Bluemix Document Conversion service with a Node.js application. I am getting nothing but errors in my app, but the test document I'm using converts fine using the demo page. Below is a minimal app that demonstrates the problem (Note that, while this app is converting a PDF from disk, the "real" app can't do that, hence the Buffer object).
'use strict';
var fs = require('fs');
var DocumentConversionV1 = require('watson-developer-cloud/document-conversion/v1');
var bluemix=require('./my_bluemix');
var extend=require('util')._extend; //Node.js' built-in object extend function
var dcCredentials = extend({
url: '<url>',
version: 'v1',
username: '<username>',
password: '<password>'
}, bluemix.getServiceCreds('document_conversion')); // VCAP_SERVICES
var document_conversion = new DocumentConversionV1(dcCredentials);
var contents = fs.readFileSync('./testdoc.pdf', 'utf8');
var parms={
file: new Buffer(contents,'utf8'),
conversion_target: 'ANSWER_UNITS', // (JSON) ANSWER_UNITS, NORMALIZED_HTML, or NORMALIZED_TEXT
content_type:'application/pdf',
contentType:'application/pdf', //don't know which of these two works, seems to be inconsistent so I include both
html_to_answer_units: {selectors: [ 'h1', 'h2','h3', 'h4']},
};
console.log('First 100 chars of file:\n******************\n'+contents.substr(0,100)+'\n******************\n');
document_conversion.convert(parms, function(err,answerUnits)
{
if (!err)
console.log('Returned '+answerUnits.length);
else
console.log('Error: '+JSON.stringify(err));
});
The results from running this program against the test PDF (782K) is:
$ node test.js
[DocumentConversion] WARNING: No version_date specified. Using a (possibly old) default. e.g. watson.document_conversion({ version_date: "2015-12-15" })
[DocumentConversion] WARNING: No version_date specified. Using a (possibly old) default. e.g. watson.document_conversion({ version_date: "2015-12-15" })
First 100 chars of file:
******************
%PDF-1.5
%����
1 0 obj
<</Type/Catalog/Pages 2 0 R/Lang(en-US) /StructTreeRoot 105 0 R/MarkInfo<<
******************
Error: {"code":400,"error":"Could not push back 82801 bytes in order to reparse stream. Try increasing push back buffer using system property org.apache.pdfbox.baseParser.pushBackSize"}
$
Can someone tell me
How to get rid of the warning messages
Why the document is not getting converted
How do I "increase the push back buffer"
Other documents give different errors, but I'm hoping if I can make this one work then the other errors will go away too.
You can get rid of the warning message by specifying a version date in your configuration. See the tests for an example. 1
If the document converted through the demo but failed to convert when using your application, it is likely an error with how the binary data is passed to the service. (For example, it's getting corrupted or truncated.) You can see the Node.js source code for the demo here 2. It may help you figure out the mistake or give you a different approach to loading/sending the file.
That is an error from one of the underlying libraries used by the service. Unfortunately, it's not something that a caller can adjust at this point.

How do I test if an img tag exists?

if I do expect(img).not.toBe(null) then I get an error:
Error: expect called with WebElement argment, expected a Promise. Did you mean to use .getText()?. I don't want to get the text inside an img, I just want to know if the tag exists on the page.
describe('company homepage', function() {
it('should have a captcha', function() {
var driver = browser.driver;
driver.get('http://dev.company.com/');
var img =driver.findElement(by.id('recaptcha_image'));
expect(img.getText()).not.toBe(null);
});
});
Passes but I'm not sure it is testing the right thing. Changing the id to something that doesn't exist does fail.
How do I properly test for a tag to exist with protractor in a non-angular app context?
Edit 2:
Per Coding Smackdown below, an even shorter answer is now available in protractor:
expect(element(by.id('recaptcha_image')).isPresent()).toBe(true);
Edit 1:
I discovered isElementPresent() today which is just a more readable shortcut for what I described below. See: http://www.protractortest.org/#/api
Usage for you would be:
driver.isElementPresent(by.id('recaptcha_image')).then(function(present){
expect(present).toBe(false);
})
Old answer (this works but the above is more reader friendly)
In general you should use findElements (or $$ which is an alias for findElements by css) if you're not sure a tag will be there. Then test for the array length. FindElement (and $) will just throw an error if it cant find the element.
Therefore instead of
var img =driver.findElement(by.id('recaptcha_image'));
expect(img.getText()).not.toBe(null);
use:
driver.findElements(by.id('recaptcha_image')).then(function(array){
expect(array.length).not.toBe(0);
})
Also, getText() returns a promise which is why you're getting that error.
Using the latest Protractor build you can shorten it down to the following:
expect(element(by.id('recaptcha_image')).isPresent()).toBe(true);