Please tell me how to write nuxt plugins 'printd' - plugins

During development, we implemented the page to print using Printd.
create plugins / printd.ts
import Vue from "vue";
import { Printd } from "printd";
Vue.use(Printd);
The 'plugins' part of nuxt.conifg.ts.
plugins: [
... ,
{ src: "~/plugins/printd", ssr: false }]
but the error is shown below
10:9 No overload matches this call.
Overload 1 of 2, '(plugin: PluginObject<unknown> | PluginFunction<unknown>, options?: unknown): VueConstructor<Vue>', gave the following error.
Argument of type 'typeof Printd' is not assignable to parameter of type 'PluginObject<unknown> | PluginFunction<unknown>'.
Property 'install' is missing in type 'typeof Printd' but required in type 'PluginObject<unknown>'.
Overload 2 of 2, '(plugin: PluginObject<any> | PluginFunction<any>, ...options: any[]): VueConstructor<Vue>', gave the following error.
Argument of type 'typeof Printd' is not assignable to parameter of type 'PluginObject<any> | PluginFunction<any>'.
Property 'install' is missing in type 'typeof Printd' but required in type 'PluginObject<any>'.
8 |
9 |
> 10 | Vue.use(Printd);
| ^
11 |
help me!!

This worked for me :
import Vue from "vue"
import { Printd } from "printd";
Vue.prototype.$Printd = new Printd();
Then you can access this.$Printd in your whole app.

Try adding: as any just like in the following.
import Vue from "vue";
import { Printd } from "printd";
Vue.use(Printd as any);
This might be your answer. But if that does not work, try this.
import Vue from "vue";
const Printd = require("printd").Printd;
Vue.use(Printd);
... And if that still does not work, try this.
file: ~/types/index.d.ts
declare module "printd"

Related

TypeError: Cannot destructure property 'createNode' of 'boundActionCreators' as it is undefined

Can anyone help with following error ?
ERROR #11321 PLUGIN
"gatsby-source-firestore" threw an error while running the sourceNodes lifecycle:
Cannot destructure property 'createNode' of 'boundActionCreators' as it is undefined.
24 | const db = firebase.firestore();
25 |
26 | const { createNode, createNodeField } = boundActionCreators;
^
27 |
28 | const promises = types.map(
29 | async ({ collection, type, populate, map = node => node }) => {
File: node_modules\gatsby-source-firestore\gatsby-node.js:26:11
TypeError: Cannot destructure property 'createNode' of 'boundActionCreators' as it is undefined.
Replacing boundActionCreators by actions in gatsby-node.js present in node modules/gatsby-source-firestore
worked

how to set babel plugins and presets - react-app-rewired

i am new to babel and testing stuff in react so it would be really great if you can provide a little more context for the approaches you can suggest.
Thank you
The app was created using react-app-rewired everything works fine but when i run my test script react-app-rewired test it throws this error
SyntaxError: C:\Users\kishan\Documents\GitHub\kp\client\src\components\DateTest\index.js: Support for the experimental syntax 'jsx' isn't currently enabled (219:5):
217 |
218 | return (
> 219 | <div className="date-test-container">
| ^
220 | <input
221 | ref={inputRef}
222 | type="text"
Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
Test file:
const React = require('react');
const {shallow} = require('enzyme')
const DateTest = require('./') // component needs to be tested
it('should render date test component and check current month',()=>{
// const wrapper = shallow(<DateTest />);
// const month = wrapper.find('span.monthName').text();
// expect(text).toEqual("March");
})
what i tried:
useBabelRc() from customize-cra can see the documentation here
Causes your .babelrc (or .babelrc.js) file to be used, this is especially useful if you'd rather override the CRA babel configuration and make sure it is consumed both by yarn start and yarn test (along with yarn build).
//inside my config-overrides.js
module.exports = override(
useBabelRc()
);
// inside my .babelrc
{
"presets": [ "#babel/preset-react"]
}
But getting the same error as above
please let me know if more information required

How can I setup Jest with a transpiler so that I can have automatically mocked DOM and canvas?

I have a small, browser-based game that I'm trying to get Jest up and running with.
My goal is to be able to write tests, and to have them run with Jest, and not to have any extra DOM- or browser API-related error messages.
As the game makes use of DOM and canvas, I need a solution where I can either mock those manually, or have Jest take care of it for me. At a minimum, I'd like to verify that the 'data model' and my logic is sane.
I'm also making use of ES6 modules.
Here's what I've tried so far:
Tried running jest:
Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/home/dingo/code/game-sscce/game.spec.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { Game } from './game';
^^^^^^
SyntaxError: Cannot use import statement outside a module
I understood here that I can experimentally enable ES module support, or use a transpiler to output ES5 that Jest can recognize and run.
So my options are:
Enable experimental ES module support
Transpile using Babel
Transpile using Parcel
Transpile using Webpack
I decided to try Babel and looked here for instructions: https://jestjs.io/docs/en/getting-started#using-babel
I created a babel.config.js file in the root directory.
After installing babel and creating a config file, here's an SSCCE:
babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env'
]
],
};
game.js
export class Game {
constructor() {
document.getElementById('gameCanvas').width = 600;
}
}
new Game();
game.spec.js
import { Game } from './game';
test('instantiates Game', () => {
expect(new Game()).toBeDefined();
});
index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script type="module" src="game.js" defer></script>
</head>
<body>
<div id="gameContainer">
<canvas id="gameCanvas" />
</div>
</body>
</html>
package.json
{
"name": "game-sscce",
"version": "1.0.0",
"scripts": {
"test": "jest"
},
"devDependencies": {
"#babel/core": "^7.12.13",
"#babel/preset-env": "^7.12.13",
"babel-jest": "^26.6.3",
"jest": "^26.6.3"
}
}
Now when I try running Jest again, I get:
FAIL ./game.spec.js
● Test suite failed to run
TypeError: Cannot set property 'width' of null
1 | export class Game {
2 | constructor() {
> 3 | document.getElementById('gameCanvas').width = 600;
| ^
4 | }
5 | }
6 |
at new Game (game.js:3:5)
at Object.<anonymous> (game.js:7:1)
at Object.<anonymous> (game.spec.js:1:1)
...and now, I'm not sure what to do. If document is not being recognized, then I suspect Jest is not making use of jsdom properly. Am I supposed to configure anything else?
Investigation:
Jest runs with jsdom by default.
document actually exists:
However, since it's mocked, getElementById() just returns null.
In this situation, it's not possible to return an existing canvas defined in the HTML document. Rather, one can create the canvas programmatically:
game.js
export class Game {
constructor() {
const canvas = document.createElement('canvas');
canvas.setAttribute('id', 'gameCanvas');
document.getElementById('gameContainer').append(canvas);
canvas.width = 600;
}
}
new Game();
getElementById() will, however, still return null, so this call must be mocked:
game.spec.js
import { Game } from './game';
test('instantiates Game', () => {
jest.spyOn(document, 'getElementById').mockReturnValue({})
expect(new Game()).toBeDefined();
});
The test still fails to run:
FAIL ./game.spec.js
● Test suite failed to run
TypeError: Cannot read property 'append' of null
3 | const canvas = document.createElement('canvas');
4 | canvas.setAttribute('id', 'gameCanvas');
> 5 | document.getElementById('gameContainer').append(canvas);
| ^
6 |
7 | canvas.width = 600;
8 |
at new Game (game.js:5:5)
at Object.<anonymous> (game.js:16:1)
at Object.<anonymous> (game.spec.js:1:1)
This is because Game is instantiating itself as soon as Jest imports it due to the new Game() call on the last line. Once rid of that:
game.js
export class Game {
constructor() {
const canvas = document.createElement('canvas');
canvas.setAttribute('id', 'gameCanvas');
document.getElementById('gameContainer').append(canvas);
canvas.width = 600;
}
}
We get:
FAIL ./game.spec.js
✕ instantiates Game (7 ms)
● instantiates Game
TypeError: document.getElementById(...).append is not a function
3 | const canvas = document.createElement('canvas');
4 | canvas.setAttribute('id', 'gameCanvas');
> 5 | document.getElementById('gameContainer').append(canvas);
| ^
6 |
7 | canvas.width = 600;
8 |
at new Game (game.js:5:46)
at Object.<anonymous> (game.spec.js:5:10)
One step closer, but the append() call must also be mocked out:
game.spec.js
import { Game } from './game';
test('instantiates Game', () => {
jest.spyOn(document, 'getElementById').mockReturnValue({
append: jest.fn().mockReturnValue({})
});
expect(new Game()).toBeDefined();
});
...and now the test passes:
PASS ./game.spec.js
✓ instantiates Game (9 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
It's interesting that jsdom returns an HTMLCanvasElement when created programmatically and mocked:
However, it can't really be used for anything:
game.js
export class Game {
constructor() {
const canvas = document.createElement('canvas');
canvas.setAttribute('id', 'gameCanvas');
document.getElementById('gameContainer').append(canvas);
canvas.width = 600;
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(200, 0, 0)';
ctx.fillRect(10, 10, 50, 50);
ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
ctx.fillRect(30, 30, 50, 50);
}
}
As shown by the failing test:
FAIL ./game.spec.js
✕ instantiates Game (43 ms)
● instantiates Game
TypeError: Cannot set property 'fillStyle' of null
10 | var ctx = canvas.getContext('2d');
11 |
> 12 | ctx.fillStyle = 'rgb(200, 0, 0)';
| ^
13 | ctx.fillRect(10, 10, 50, 50);
14 |
15 | ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
at new Game (game.js:12:5)
at Object.<anonymous> (game.spec.js:7:10)
console.error
Error: Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package)
at module.exports (/home/dingo/code/game-sscce/node_modules/jsdom/lib/jsdom/browser/not-implemented.js:9:17)
at HTMLCanvasElementImpl.getContext (/home/dingo/code/game-sscce/node_modules/jsdom/lib/jsdom/living/nodes/HTMLCanvasElement-impl.js:42:5)
at HTMLCanvasElement.getContext (/home/dingo/code/game-sscce/node_modules/jsdom/lib/jsdom/living/generated/HTMLCanvasElement.js:130:58)
at new Game (/home/dingo/code/game-sscce/game.js:10:22)
at Object.<anonymous> (/home/dingo/code/game-sscce/game.spec.js:7:10)
at Object.asyncJestTest (/home/dingo/code/game-sscce/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:106:37)
at /home/dingo/code/game-sscce/node_modules/jest-jasmine2/build/queueRunner.js:45:12
at new Promise (<anonymous>)
at mapper (/home/dingo/code/game-sscce/node_modules/jest-jasmine2/build/queueRunner.js:28:19)
at /home/dingo/code/game-sscce/node_modules/jest-jasmine2/build/queueRunner.js:75:41 undefined
8 | canvas.width = 600;
9 |
> 10 | var ctx = canvas.getContext('2d');
| ^
11 |
12 | ctx.fillStyle = 'rgb(200, 0, 0)';
13 | ctx.fillRect(10, 10, 50, 50);
To be able to test further, either of the following two conditions must be fulfilled:
canvas has to be installed as a peer dependency of jsdom,
jest-canvas-mock has to be installed.

`basename` argument not specified

i created a new project by django restframework
the project name = frame
th project_app name= framework
fram.urls.py:
"""frame URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path
from django.conf.urls import include,url
from framework.views import myviewset
from rest_framework import routers
router = routers.DefaultRouter();
router.register('task', myviewset)
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'', include(router.urls)),
]
framework models.py:
from django.db import models
# Create your models here.
class Task (models.Model):
task_name=models.CharField(max_length='200')
task_desc=models.CharField(max_length='200')
date_created=models.DateTimeField(auto_now=True)
serializer.py
from .models import Task
from rest_framework import serializers
class TaskSerializers(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('id', 'task_name', 'task_desc')
views.py:
from django.shortcuts import render
from .serializer import TaskSerializers
from rest_framework import viewsets
from .models import Task
# Create your views here.
class myviewset(viewsets.ModelViewSet):
query = Task.objects.all().order_by('date_created')
serializer_class = TaskSerializers
admin.py:
from django.contrib import admin
from .models import Task
admin.site.register(Task)
# Register your models here.
setting.py:
INSTALLED_APPS = [
'framework',
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
when i run th server in CMD
this error comes :
AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute.
You should specify queryset attribute instead of query in your viewset. For example (class name case changed to comply PEP8):
class MyViewSet(viewsets.ModelViewSet):
queryset = Task.objects.all().order_by('date_created')
serializer_class = TaskSerializers
Docs: https://www.django-rest-framework.org/api-guide/viewsets/#modelviewset
Also I recommend always specify basename when you register your viewsets. Like this:
router = routers.DefaultRouter();
router.register('task', MyViewSet, basename='tasks')
https://www.django-rest-framework.org/api-guide/routers/#usage
basename - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set basename when registering the viewset.

Yeoman Generator in CoffeeScript - HookFor Warning

I'm trying to develop a custom generator for Yeoman using CoffeeScript but I'm facing a problem. When I use the hookFor method in the constructor of my class Generator, I get a warning hookFor must be used within the constructor when I try to init my project with Yeoman and my custom generator. Here is the code of my generator in index.coffee :
path = require 'path'
util = require 'util'
yeoman = require '../../../../'
module.exports = class Generator extends yeoman.generators.Base
constructor: ->
super()
#directories = ['controllers', 'helpers', 'models', 'templates', 'views']
#hookFor 'artefact:controller', args: ['App']
deploy: ->
#directory '.', '.'
#mkdir path.join 'dev', directory for directory in #directories
Any help will be appreciated. Thanks.
Apparently, the error comes from Yeoman Generators code in the yeoman-generators/lib/base.js file.
Here is how I led to that conclusion :
The warning is caused by the variable _running set to true in hookFor function (line 296)
This variable is set to true in run function (line 78) and just after that, methods of the class Generator are iterated (line 81-137)
the constructor defined in CoffeeScript for the class Generator is called during the iteration, so #hookFor is called whereas _running is true : warning!
But, the constructor should not be called because a test is done during the iteration to prevent it (line 92) :
if ( method.constructor === '-' )
However, this test, in my opinion, should be :
if ( method === 'constructor' )
The hack does the trick. Feel free to add comment if I'm wrong.