Cannot find module 'firebase-admin' from 'index.cjs.js' - firebase

I was using #firebase/testing on Jest, but since it's deprecated and instructed to use new one, I decided to move to #firebase/rules-unit-testing.
Here is the code where I just switched them.
import { initializeAdminApp } from "#firebase/rules-unit-testing";
import "babel-polyfill";
it("is ok", async () => {
const admin = initializeAdminApp({ projectId: "my-project" });
try {
const doc = admin.firestore().collection("items").doc("item-1");
await doc.set({ name: "Item 1" });
const ss = await doc.get();
expect(ss.data()?.name).toBe("Item 1");
} finally {
await admin.delete();
}
});
When I run this test with emu, it results "Cannot find module 'firebase-admin' from 'index.cjs.js'" error.
Cannot find module 'firebase-admin' from 'index.cjs.js'
3 |
4 | it("is ok", async () => {
> 5 | const admin = initializeAdminApp({ projectId: "my-project" });
| ^
It passes if it is the old #firebase/testing.
What did I miss?
Node.js v14.8.0
Jest 25.5.4
firebase 7.21.1
firebase-tools 8.11.2
#firebase/testing 0.20.11
#firebase/rules-unit-testing 1.0.4

The firebase-admin is an npm package. Just installed it and all worked.
$ npm install -D firebase-admin

I started to use firebase-admin#^10.0.1 and I had this error when running jest tests. It couldn't map "firebase-admin/app" to "firebase-admin/lib/app" as expected. So I have mapped this manually on jest.config.ts:
import { pathsToModuleNameMapper } from 'ts-jest/utils';
import { compilerOptions } from './tsconfig.json';
...
export default {
...
moduleNameMapper: pathsToModuleNameMapper(
{
...compilerOptions.paths,
'firebase-admin/*': ['node_modules/firebase-admin/lib/*'],
},
{
prefix: '<rootDir>',
},
),
...
}
That worked for me.
And just to note, my tsconfig.json is like this:
{
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"modules/*": [
"src/modules/*"
],
"shared/*": [
"src/shared/*"
],
}
}
}

Related

Coinbase wallet not open always ask to install even its installed on deploy to server but opens in local, using wagmi and next js

I have used wagmi for wallet connect and using next js , the wallet trigger and open extension of coinbase in local but when we deploy it on sever it always tell to install even though it is already installed. I am sharing my connection tried using both alchemy and infura provider but not working . Any idea anybody.shared pic the wallet is installed but still it ask to install
import {
configureChains,
createClient,
goerli,
mainnet,
WagmiConfig,
} from "wagmi";
import { alchemyProvider } from "wagmi/providers/alchemy";
import { infuraProvider } from "wagmi/providers/infura";
import { publicProvider } from "wagmi/providers/public";
import { ReactNode } from "react";
import { CoinbaseWalletConnector } from "wagmi/connectors/coinbaseWallet";
import { MetaMaskConnector } from "wagmi/connectors/metaMask";
import { WalletConnectConnector } from "wagmi/connectors/walletConnect";
interface WalletProviderInterface {
children: ReactNode;
}
const WalletProvider = ({ children }: WalletProviderInterface) => {
const { chains, provider, webSocketProvider } = configureChains(
[mainnet],
[
alchemyProvider({
apiKey: process.env.NEXT_PUBLIC_ALCHEMY_KEY || "",
}),
infuraProvider({ apiKey: process.env.NEXT_PUBLIC_INFURA_KEY || "" }),
]
);
const connectors = [
new MetaMaskConnector({
chains,
options: {
shimDisconnect: true,
shimChainChangedDisconnect: false,
},
}),
new CoinbaseWalletConnector({
chains,
options: {
appName: `test app`,
jsonRpcUrl: `https://ethmainnet.g.alchemy.com/v2/${process.env.NEXT_PUBLIC_ALCHEMY_KEY}`,
},
}),
new WalletConnectConnector({
chains,
options: {
// alchemyId:process.env.NEXT_PUBLIC_ALCHEMY_KEY,
qrcode: true,
},
}),
];
const client = createClient({
autoConnect: true,
connectors,
provider,
webSocketProvider,
});
return <WagmiConfig client={client}>{children}</WagmiConfig>;
};
export default WalletProvider;

nextjs: TypeError: createServer is not a function

I am trying to follow this tutorial:
I am stuck at step 3, which is where the server is defined as follows:
import { createServer } from "#graphql-yoga/node";
import { join } from "path";
import { readFileSync } from "fs";
const typeDefs = readFileSync(join(process.cwd(), "schema.graphql"), {
encoding: "utf-8",
});
const resolvers = {
Query: {
cart: (_, { id }) => {
return {
id,
totalItems: 0,
};
},
},
};
const server = createServer({
cors: false,
endpoint: "/api",
logging: {
prettyLog: false,
},
schema: {
typeDefs,
resolvers,
},
});
export default server;
When I try to use that definition and start the local host, I get an error that says:
TypeError: (0 ,
graphql_yoga_node__WEBPACK_IMPORTED_MODULE_0_.createServer) is not a function at eval
Can anyone see if this tutorial is now out of date. I can see that I am using next v 13.1.1 and the tutorial uses v12. I've been having an awful time trying to find an explanation of how to use these packages, in their current formats. Is this one now out of date?
Can anyone see how to define a server for next v13?
There are some change between graph-yoga v2 and v3, you can look this tutorial to solve it.
For others that might be stuck, this might be a way to define the schema using graphql-yoga (now instead of graphql-yoga/node)
import { createSchema, createYoga } from 'graphql-yoga'
import { createServer } from 'node:http'
import { join } from "path";
import { readFileSync } from "fs";
const typeDefs = readFileSync(join(process.cwd(), "schema.graphql"), {
encoding: "utf-8",
});
const resolvers = {
Query: {
cart: (_, { id }) => {
return {
id,
totalItems: 0,
};
},
},
};
const yoga = createYoga({
cors: false,
endpoint: "/api",
logging: {
prettyLog: false,
},
schema: createSchema({
typeDefs,
resolvers,
}),
});
const server = createServer(yoga);
server.listen(3000, () => {
console.info('Server is running on http://localhost:3000/graphql')
});
export default server;

Having difficulty setting up pinia stores in nuxt 3

I'm currently trying to setup a project using nuxt 3 with pinia for state management and I have bumped into the following error:
[h3] [unhandled] H3Error: defineStore is not defined
at createError (file:///home/johnr/Code/Personal/test/node_modules/h3/dist/index.mjs:191:15)
at Server.nodeHandler (file:///home/johnr/Code/Personal/test/node_modules/h3/dist/index.mjs:381:21) {
statusCode: 500,
fatal: false,
unhandled: true,
statusMessage: 'Internal Server Error'
}
I initialized the project with npx nuxi init and then ran npm i, followed by npm install #pinia/nuxt. I then added pinia to nuxt.config.ts:
// nuxt.config.js
export default {
// ... other options
modules: [
// ...
'#pinia/nuxt',
],
}
and created a basic store in store/counter.js:
export const useCounterStore = defineStore('counter', () => {
const count = ref(0);
function increment() {
count.value++;
}
return { count, increment };
});
and have tried to use the returned count in the app template:
<template>
<div>
<p>The count is {{ counterStore.count.value }}</p>
</div>
</template>
<script setup>
import { useCounterStore } from './store/counter.js';
const counterStore = useCounterStore();
</script>
It looks like you forgot to import defineStore in store/counter.js:
import { defineStore } from 'pinia'

Vue3 testing ElementPlus controls with vitest

I am running Vue3 with vite and can't write any tests for components that use the ElementPlus library. Something else needs to be injected apparently but I don't know how to do that.
I have the following dateControl.test.js:
import { describe, expect, test } from 'vitest';
import { ref } from 'vue';
import DateCtrl from '#/components/DateCtrl.vue';
import { mount } from "#vue/test-utils";
import ElementPlus from "element-plus";
describe("DateCtrl.vue", () => {
const messages = {
"en-US" : {
strings: {
placeholder: 'a',
label: 'b'
}
}
};
const locale = "en-US";
const data = ref ({
date: ''
});
test ("Arrange DateCtrl", async () => {
const component = mount(DateCtrl, {
props: {
vModel: data.value.date,
modelValue: data.value.date,
labelLoc: "label",
className: "w1x5",
placeholderLoc: "date"
},
global: {
plugins: [ElementPlus],
mocks: {
$t: (msg) => {
const params = msg.split('.');
return messages[locale][params[0]][params[1]];
}
}
}
});
//fails on previous lines.
expect(typeof component !== "undefined", "component created").toBeTruthy();
let h3Text = component.findAll('h3')[0].element.innerHTML;
expect(component.findAll('.form').length === 1, "form element rendered").toBeTruthy();
expect(h3Text === "d", "locale strings correct").toBeTruthy();
});
});
It doesn't even get to the "expect" tests, fails with message:
Error: Cannot find module 'C:\source\mySite\node_modules\dayjs\plugin\customParseFormat'
imported from
C:\source\mySite\node_modules\element-plus\es\components\date-picker\src\date-picker.mjs
Did you mean to import dayjs/plugin/customParseFormat.js?
This bit seems to indicate that node expects you to use .js extension and element is not doing that.
Error: Cannot find module 'C:\source\mySite\node_modules\dayjs\plugin\customParseFormat'
imported from
C:\source\mySite\node_modules\element-plus\es\components\date-picker\src\date-picker.mjs
Did you mean to import dayjs/plugin/customParseFormat.js?
I'm guessing this is because you may be running an older node version. Element requires at least node v16.
I have this problem too.
It seems that this problem is already solved in this pull request - https://github.com/element-plus/element-plus/pull/6811

How to precache ALL pages with next-pwa

How would I go about precaching all the pages of my nextjs app using next-pwa?. Let's say I have the following pages:
/
/about
/posts
I want all of them to be precached so that they are all available offline once the app has been loaded the first time. At the moment I'm using a custom webpack config to copy the .next/build-manifest.json file over to public/build-manifest. Then once the app loads the first time, I register an activated handler that fetches the build-manifest.json file and then adds them to the cache. It works but it seems like a roundabout way of achieving it, and it depends somewhat on implementation details. How would I accomplish the same in a more canonical fashion?
At the moment, my next.config.js file looks like this
const pwa = require('next-pwa')
const withPlugins = require('next-compose-plugins')
const WebpackShellPlugin = require('webpack-shell-plugin-next')
module.exports = withPlugins([
[
{
webpack: (config, { isServer }) => {
if (isServer) {
config.plugins.push(
new WebpackShellPlugin({
onBuildExit: {
scripts: [
'echo "Transfering files ... "',
'cp -r .next/build-manifest.json public/build-manifest.json',
'echo "DONE ... "',
],
blocking: false,
parallel: true,
},
})
)
}
return config
},
},
],
[
pwa,
{
pwa: {
dest: 'public',
register: false,
skipWaiting: true,
},
},
],
])
And my service worker hook looks like this
import { useEffect } from 'react'
import { Workbox } from 'workbox-window'
export function useServiceWorker() {
useEffect(() => {
if (
typeof window !== 'undefined' &&
'serviceWorker' in navigator &&
(window as any).workbox !== undefined
) {
const wb: Workbox = (window as any).workbox
wb.addEventListener('activated', async (event) => {
console.log(`Event ${event.type} is triggered.`)
console.log(event)
const manifestResponse = await fetch('/build-manifest.json')
const manifest = await manifestResponse.json()
const urlsToCache = [
location.origin,
...manifest.pages['/[[...params]]'].map(
(path: string) => `${location.origin}/_next/${path}`
),
`${location.origin}/about`,
...manifest.pages['/about'].map((path: string) => `${location.origin}/_next/${path}`),
`${location.origin}/posts`,
...manifest.pages['/posts'].map((path: string) => `${location.origin}/_next/${path}`),
]
// Send that list of URLs to your router in the service worker.
wb.messageSW({
type: 'CACHE_URLS',
payload: { urlsToCache },
})
})
wb.register()
}
}, [])
}
Any help is greatly appreciated. Thanks.

Resources