Cannot find module babel-preset-es2015 in cypress - cypress

The erros occurs when i add
const replace = require("replace-in-file"); in file to my code
const replace = require("replace-in-file");
const options = {
files: "./config/dashboardData.json",
configFile: true,
from: /}\n{/g,
to: ",\n",
};
I have installed babel and configured the preset still I got the issue

The package replace-in-file handles files on the OS, so it needs to be called from Node.
You would need to set up a Cypress task.
In Cypress ver 10+, do this in cypress.config.js
// cypress.config.js
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('task', {
replaceTask(options) {
const replace = require("replace-in-file");
try {
const results = replace.sync(options);
return results
}
catch (error) {
return error
}
},
})
},
// other e2e configuration here
},
});
// test.spec.cy.js
it('calls replace-in-file', () => {
const options = {
files: "./config/dashboardData.json",
configFile: true,
from: /}\n{/g,
to: ",\n",
};
cy.task('replaceTask', options).then(resultsOrError => {
console.log(resultsOrError)
})
});

Related

SCSS Modules not properly loading in Storybook for my Nextjs app

Working on a new project using Nextjs and Storybook. We are using SCSS modules to style our components, and they work just fine in the actual app on the browser, but they won't link up in the stories themselves. Here are a few simple snippets to show where I'm at right now:
Component:
import React from 'react'
import styles from './VideoEntryTile.module.scss'
const VideoEntryTile: React.FC = () => {
return (
// This displays properly in the browser but not storybook
<div className={styles.container}>
<p>Hello</p>
</div>
)
}
export default VideoEntryTile
SCSS module:
.container {
background-color: blueviolet;
}
Component story:
import React from 'react';
import { ComponentStory, ComponentMeta } from '#storybook/react';
import VideoEntryTile from './VideoEntryTile';
export default {
title: 'Video Entry Tile',
component: VideoEntryTile,
argTypes: {
},
} as ComponentMeta<typeof VideoEntryTile>;
const Template: ComponentStory<typeof VideoEntryTile> = (args) => <VideoEntryTile {...args} />;
export const Primary = Template.bind({});
Primary.args = {};
./storybook/main.js:
module.exports = {
core: {
builder: 'webpack5',
},
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)",
"../src/components/**/*.stories.tsx"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials",
{
name: '#storybook/preset-scss',
options: {
sassLoaderOptions: {
modules: true
}
}
}
],
"framework": "#storybook/react"
}
Can anyone tell me where I'm going wrong? Thanks.
Create a file called scss-preset.js in .storybook:
// Copied from https://github.com/storybookjs/presets/blob/master/packages/preset-scss/index.js
function wrapLoader(loader, options) {
if (options === false) {
return [];
}
return [
{
loader,
options,
},
];
}
function webpack(webpackConfig = {}, options = {}) {
const { module = {} } = webpackConfig;
const {
styleLoaderOptions,
cssLoaderOptions,
sassLoaderOptions,
rule = {},
} = options;
return {
...webpackConfig,
module: {
...module,
rules: [
...(module.rules || []),
{
test: /(?<!module)\.s[ca]ss$/,
...rule,
use: [
...wrapLoader('style-loader', styleLoaderOptions),
...wrapLoader('css-loader', {
...cssLoaderOptions,
modules: false,
}),
...wrapLoader('sass-loader', sassLoaderOptions),
],
},
{
test: /\.module\.s[ca]ss$/,
...rule,
use: [
...wrapLoader('style-loader', styleLoaderOptions),
...wrapLoader('css-loader', {
...cssLoaderOptions,
modules: true,
}),
...wrapLoader('sass-loader', sassLoaderOptions),
],
},
],
},
};
}
module.exports = { webpack };
This is going through each scss file and, if it's a module.scss file, processing it differently than the ones that aren't.
in main.js, add presets: [path.resolve("./.storybook/scss-preset.js")], to module.exports. Should be all you need.
Make sure you have installed sass
npm install sass --save
Install scss preset
npm install #storybook/preset-scss --save
Add it to the addons list inside your .storybook/main.js
addons: ['#storybook/preset-scss',]

Redux saga failed in production

I've been trying to tackle this problem more than 2 weeks now. Everything works fine in development mode. But not in production mode. The example below are shown using Redux Saga environment (I'm still new in redux saga). But I've tried re-do it using Context API. Unfortunately the problem still persists. (below are the images showing successful process in development mode & unsuccessful process in production mode)
successful in development mode
unsuccessful in production mode
My guess it could be something to do with status code 304 Not Modified. Since the data I tried to fetch not changing, thus it will use cached data in browser. But I don't know how to setup my server so that I can handle this issue. I have read a bunch of online threads. But none were able to resolve my issue.
You may have a look at my code right now. Bear in mind that everything works just fine in development mode. From the images above you can see that I don't have problem logging in. Just fetching & getting data to be displayed in dashboard got error.
client/src/redux/actions/Dashboard.js (Action)
import { SET_ISDASHBOARD, SET_LOADING, SET_ERROR } from '../sagas/types'
// Set Loading
export const setLoading = (status) => ({
type: SET_LOADING,
payload: status
})
// Set Error
export const setError = (error) => ({
type: SET_ERROR,
payload: { error: error.status, message: error.message }
})
// Dashboard
export const isDashboard = () => ({
type: SET_ISDASHBOARD
})
client/src/redux/reducers/Dashboard.jd (Reducer)
import { SET_ERROR, SET_LOADING, SET_ISDASHBOARD, SET_DASHBOARD } from '../sagas/types'
const initialState = {
user: {
id: '',
name: '',
email: ''
},
loading: false,
error: false,
message: ''
}
const reducer = (state = initialState, action) => {
switch(action.type) {
case SET_ISDASHBOARD:
return {
...state,
loading: true
}
case SET_DASHBOARD:
return {
...state,
user: {
...state.user,
id: action.payload.id,
email: action.payload.email,
name: action.payload.name
}
}
case SET_ERROR:
return {
...state,
error: action.payload.status,
message: action.payload.message
}
case SET_LOADING:
return {
...state,
loading: action.payload
}
default:
return state
}
}
export default reducer
client/src/redux/sagas/handlers/dashboard.js (Saga handlers)
import { call, put } from 'redux-saga/effects'
import { requestGetDashboard } from '../requests/dashboard'
import { SET_LOADING, SET_ERROR, SET_DASHBOARD } from '../types'
export function* handleGetDashboard(action) {
try {
const response = yield call(requestGetDashboard)
const result = response.data.data
console.log(response); console.log(result)
// dispatch set dashboard
yield put({ type: SET_DASHBOARD, payload: { id: result.id, email: result.email, name: result.name } })
} catch(error) {
// console.log(error); console.log(error.response)
const result = error.response.data
const payload = {
status: true,
message: result.error
}
// dispatch setError
yield put({ type: SET_ERROR, payload: payload })
}
// loading to false
yield put({ type: SET_LOADING, payload: false })
}
client/src/redux/sagas/requests/dashboard.js (Saga requests)
import axios from 'axios'
/** get dashboard */
export const requestGetDashboard = () => {
return axios.get(
'/api/v1/dashboard',
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem('uid')}`
}
}
)
}
client/src/redux/sagas/rootSaga.js (Root Saga)
import {
SET_ISLOGIN, SET_ISLOGOUT, SET_ISAUTH,
SET_ISDASHBOARD,
} from './types'
import { takeLatest } from 'redux-saga/effects'
import { handleClientAuth, handlePostLogin, handlePostLogout } from './handlers/auth'
import { handleGetDashboard } from './handlers/dashboard'
export function* watcherSaga() {
// auth
yield takeLatest(SET_ISLOGIN, handlePostLogin)
yield takeLatest(SET_ISLOGOUT, handlePostLogout)
yield takeLatest(SET_ISAUTH, handleClientAuth)
// dashboard
yield takeLatest(SET_ISDASHBOARD, handleGetDashboard)
}
client/src/redux/sagas/types.js (Types)
/** for AUTH */
export const SET_ISLOGIN = 'SET_ISLOGIN'
export const SET_ISLOGOUT = 'SET_ISLOGOUT'
export const SET_ISAUTH = 'SET_ISAUTH'
export const SET_AUTH = 'SET_AUTH'
export const SET_LOADING = 'SET_LOADING'
export const SET_ERROR = 'SET_ERROR'
/** for DASHBOARD */
export const SET_ISDASHBOARD = 'SET_ISDASHBOARD'
export const SET_DASHBOARD = 'SET_DASHBOARD'
Please point me to any directions that could help get closer insight to this problem.

Read excel files in Cypress

I am new to Cypress. How to read data from excel files using Cypress? Searched in google but could not find useful answers.
In cypress you can create cypress task to read xlsx file with SheetJS library.
Usage
cypress\integration\read-xlsx.spec.js
context('Xlsx file', () => {
it('Read excel file', () => {
cy.task('readXlsx', { file: 'my-excel.xlsx', sheet: "Sheet1" }).then((rows) => {
expect(rows.length).to.equal(543)
// expect(rows[0]["column name"]).to.equal(11060)
})
})
})
Need to install xlsx
$ npm install xlsx
Create read excel fuction
cypress\plugins\read-xlsx.js
const fs = require('fs');
const XLSX = require('xlsx');
const read = ({file, sheet}) => {
const buf = fs.readFileSync(file);
const workbook = XLSX.read(buf, { type: 'buffer' });
const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
return rows
}
module.exports = {
read,
}
Use function as Cypress task (plugin)
cypress\plugins\index.js
const readXlsx = require('./read-xlsx')
module.exports = (on, config) => {
on('task', {
'readXlsx': readXlsx.read
})
}
Here is an instruction how to use excel as source for cypress tests https://medium.com/#you54f/dynamically-generate-data-in-cypress-from-csv-xlsx-7805961eff55
First you need to conver your xlsx file to json with Xlsx
import { writeFileSync } from "fs";
import * as XLSX from "xlsx";
try {
const workBook = XLSX.readFile("./testData/testData.xlsx");
const jsonData = XLSX.utils.sheet_to_json(workBook.Sheets.testData);
writeFileSync(
"./cypress/fixtures/testData.json",
JSON.stringify(jsonData, null, 4),
"utf-8"
);
} catch (e) {
throw Error(e);
}
Then import json file and loop over each row and use the data in the way you want. In this example it tries to log in to a system.
import { login } from "../support/pageObjects/login.page";
const testData = require("../fixtures/testData.json");
describe("Dynamically Generated Tests", () => {
testData.forEach((testDataRow: any) => {
const data = {
username: testDataRow.username,
password: testDataRow.password
};
context(`Generating a test for ${data.username}`, () => {
it("should fail to login for the specified details", () => {
login.visit();
login.username.type(data.username);
login.password.type(`${data.password}{enter}`);
login.errorMsg.contains("Your username is invalid!");
login.logOutButton.should("not.exist");
});
});
});
});
For me the first answer pretty much worked. But i had to make a small fix.
Use function as Cypress task (plugin)
cypress/plugins/index.js
const readXlsx = require('./read-xlsx')
module.exports = (on, config) => {
on('task', {
'readXlsx': readXlsx.read
})
}
when i used this code i got the below error in cypress.
CypressError
cy.task('log') failed with the following error:
The task 'log' was not handled in the plugins file. The following tasks are registered: readXlsx
and the below fix worked
const readXlsx = require('./read-xlsx')
module.exports = (on, config) => {
on('task', {
'readXlsx': readXlsx.read,
log (message) {
console.log(message)
return null
}
})
}

How to Unit Test Graphql Resolver functions created using apollo-resolvers

I have created resolvers(userresolver.js) using 'apollo-resolvers' npm module as below.
import { createResolver } from 'apollo-resolvers';
import { isInstance } from 'apollo-errors';
const baseResolver = createResolver(
null,
(root, args, context, error) => isInstance(error) ? error : new UnknownError()
);
const users = baseResolver.createResolver(
(parent, args, { models, me } ) => {
return Object.values(models.users);
}
);
export default {
Query: {
users
}
}
;
These also work fine when I test the queries after starting the server.
I now want to do unit testing of the resolver functions.
I am not sure how to do that. Can someone help me on how to unit test the resolver functions. I am using mocha with chai for testing my project.
You can try easygraphql-tester, it has a method that'll help you to test the resolvers.
Here is the documentation of it.
Example:
Resolver
"use strict";
const license = (__, args, ctx) => {
const { key } = args;
return {
id: "1234",
body: "This is a test license",
description: `This is a description with key ${key}`
};
};
module.exports = {
Query: {
license
}
};
Test
"use strict";
const fs = require("fs");
const path = require("path");
const { expect } = require("chai");
const EasyGraphQLTester = require("easygraphql-tester");
const resolvers = require("../resolvers");
const schemaCode = fs.readFileSync(
path.join(__dirname, "..", "schema.gql"),
"utf8"
);
describe("Test resolvers", () => {
let tester;
beforeAll(() => {
tester = new EasyGraphQLTester(schemaCode, resolvers);
});
it("should return expected values", async () => {
const query = `
query GET_LICENSE($key: String!) {
license(key: $key) {
id
body
description
}
}
`;
const args = {
key: "1234"
};
const result = await tester.graphql(query, {}, {}, args);
expect(result.data.license.id).to.be.eq("1234");
expect(result.data.license.body).to.be.eq("This is a test license");
expect(result.data.license.description).to.be.eq(
`This is a description with key ${args.key}`
);
});
});

Calls to Dispatcher.register return `undefined`

new to Jest and having trouble with getting up and running. When calling Dispatcher.register, all I get is undefined.
I'm running Node.js 5.7.0 and Jest 0.9.2.
The following test fails:
BookedServicesStore-test.js:
jest.unmock("../BookedServicesStore");
jest.unmock("object-assign");
describe("BookedServicesStore", () => {
let BookedServicesStore;
let AppDispatcher;
beforeEach(() => {
BookedServicesStore = require("../BookedServicesStore");
AppDispatcher = require("../../dispatcher/AppDispatcher");
});
it("has a dispatch token", () => {
expect(BookedServicesStore.dispatchToken).not.toBeUndefined();
});
});
BookedServicesStore.js:
import AppDispatcher from "../dispatcher/AppDispatcher";
import { EventEmitter } from "events";
import assign from "object-assign";
const CHANGE_EVENT = "change";
const BookedServicesStore = assign({}, EventEmitter.prototype, {
emitChange() {
this.emit(CHANGE_EVENT);
},
addChangeListener(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener(callback) {
this.removeListener(CHANGE_EVENT, callback);
}
// ...
});
BookedServicesStore.dispatchToken = AppDispatcher.register(action => {
// ...
});
module.exports = BookedServicesStore;
AppDispatcher.js:
import { Dispatcher } from "flux";
module.exports = new Dispatcher();
Not sure what's going on here. What is it that I'm missing?

Resources