Categories
Vue Answers

How to fix Vue js error: Component template should contain exactly one root element?

To fix Vue js error: Component template should contain exactly one root element, we should wrap our elements with one root element in our template.

For instance, we write

<div>
  <div class="form-group">...</div>

  <div class="col-md-6">...</div>
</div>

to wrap a div around the other divs to clear the error.

Categories
JavaScript Answers

How to fix ‘TypeError: is not a function’ error in Node.js?

To fix ‘TypeError: is not a function’ error in Node.js, we should make sure the variable is a function.

For instance, we write

module.exports = functionName

to export the functionName function in function.js.

Then we require it with

const functionName = require('./function')

Now we can call functionName in our code.

Categories
JavaScript Answers

How to check if token expired using this JWT library in Node.js?

To check if token expired using this JWT library in Node.js, we get the expiration timestamp and compare it to the current date and time.

For instance, we write

const isTokenExpired = (token) =>
  Date.now() >= JSON.parse(atob(token.split(".")[1])).exp * 1000;

to get the token’s expiration timestamp in milliseconds with

JSON.parse(atob(token.split(".")[1])).exp * 1000

Then we compare it to the current timestamp returned by Date.now.

If the current timestamp is bigger than the token’s timestamp, then the token expired.

Categories
JavaScript Answers

How to change working directory for npm scripts?

To change working directory for npm scripts, we run cd before running our script.

For instance, we write

cd dir && command -args

in our npm script to change the directory to dir with cd before running command with the -args flags.

Categories
JavaScript Answers

How to stub process.env in Node.js?

To stub process.env in Node.js, we set the values in our test.

For instance, we write

it("does something interesting", () => {
  process.env.NODE_ENV = "test";
  // ...
});

afterEach(() => {
  delete process.env.NODE_ENV;
});

to set the process.env.NODE_ENV to 'test' in our test.

And we delete the property in the afterEach callback so it’s removed after each test.