we are using ngxs and we do have some lazy selectors defined in separated files from the state definition
export class SectionSelectors {
#Selector([CatalogState])
static ById(state: CatalogModel) {
return function getSectionById(id: number): Section {
const selectedSection: Section = state.sections[id];
return selectedSection;
};
}
}
And we have test cases like
import { TestBed } from '#angular/core/testing';
import { Section } from '#miq-catalog/catalog';
import { NgxsModule, Store } from '#ngxs/store';
import { CatalogModel, CatalogState } from './catalog.state';
import { SectionSelectors } from './section.selectors';
describe('SectionSelectors', () => {
it('should select the section by id', () => {
const one: Section = { sectionId: 1, title: '', columns: [] };
const two: Section = { sectionId: 2, title: '', columns: [] };
const state: CatalogModel = {
catalog: [],
sections: { 1: one, 2: two },
columns: {},
catalogLoaded: true,
};
const selectionFunction = SectionSelectors.ById(state);
const result = selectionFunction(1);
expect(result).toBeDefined();
expect(result).toBe(one);
expect(result.sectionId).toBe(1);
const result2 = selectionFunction(2);
expect(result2).toBeDefined();
expect(result2).toBe(two);
expect(result2.sectionId).toBe(2);
});
});
We are passing the state to the selector however we are getting the next error
An error was thrown in afterAll
Uncaught ReferenceError: Cannot access 'CatalogState' before initialization
ReferenceError: Cannot access 'CatalogState' before initialization
I noticed that if I move these selector to the CatalogState (where the #State definition is) the problem is fixed. But this is forcing us to put all selectors there and we think it's good to have them scoped on their own related files so we don't "pollute" with mixed selectors.
Is there a way we can fix the test case? Does someone already faced this Lazy Selector testing before?
As complementary info this is how our State looks like
#State({
name: 'Catalog',
defaults: {
catalogLoaded: false,
columns: {},
sections: {},
catalog: [],
},
})
export class CatalogState {
constructor(private store: Store) {}
#Action(RetrieveCatalogInfo)
#Action(ChangeColumnConfig)
#Action(ClearCatalog)
public executeAction(ctx: StateContext<CatalogModel>, params: ExecutableAction<CatalogModel>) {
return params.execute({ ctx, store: this.store });
}
}
This should not be a problem with the latest version of NGXS (since v3.6.1).
Related
The component itself works on the page with no errors.
So does storybook, the only issue is the unit test.
import { mount } from '../../vue';
import { createLocalVue } from '#vue/test-utils';
import Vuex from 'vuex';
import SessionGymChart from '#/components/SessionGymChart.vue';
const localVue = createLocalVue();
localVue.use(Vuex);
const defaultprops = {
endDateOveride: '',
totalHours: 0,
sessionsTotal: 1,
isLoading: false,
hasTooMuchData: false,
swapChart: false,
chartData: {}
};
describe('SessionGymChart', () => {
let store;
beforeEach(() => {
store = new Vuex.Store({
state: {
user: { billing: true },
chartData: {
days: 10,
sessions: [
{
id: '324365egdfgfd',
sessionReference: '056343',
dateStarted: '2022-08-26T16:23:14.909Z',
dateEnded: '2022-08-26T16:23:22.000Z',
userId: 'dfgdfgdfg545645',
userDisplayName: 'Tester'
}
]
}
},
mutations: {},
actions: {}
});
});
Is there anything obvious I'm doing wrong?
There is a computed property where it breaks on the component. It seems like it can't access the sessions data (saying undefined) and I'm not sure why as it is inside defaultprops.
This is where it shows to be breaking in the component, at a computed property and this shows on the snapshot error.
gymSeries() {
const { sessions } = this.chartData ? this.chartData : {};
> if (sessions.length === 0) return {};
^
else {
const sessionsUsage = sessions.map(x => {
return {
Any help would be much appreciated!
This actually returns undefined if this.chartData is undefined:
const { sessions } = this.chartData ? this.chartData : {};
The problem there is that you're destructuring chartData, and you expect the return value of the ternary statement to be an object that contains a sessions property.
If chartData is undefined, that results in:
const { sessions } = {};
You can fix that by adding an empty sessions property:
const { sessions } = this.chartData ? this.chartData : { sessions: {} };
Or, shorter, using optional chaining:
const sessions = this.chartData?.sessions || {};
I am trying to write a simple test for my vue component. Since the vue component makes an async call on mount and updates the vuex store, dispatch is called during mount, which breaks my existing unit tests. Any idea how to overcome this? Since I am mocking table data, I don't need the mounted() function to be called when running the tests.
MyTable.spec.js
const wrapper = shallowMount(MyTable, {
propsData: {
tableData: [
{
"product_id":10826345236,
"name":"T-Shirt"
}
],
columns: ['product_id', 'name'],
headings: ['Product ID', 'Name'],
actionType: 'loadProducts'
}
});
...
MyTable.vue
...
data() {
return {
options: {
...
}
};
},
methods: {
getHeadings() {
let headings = {};
this.columns.map((key, i) => headings[key] = this.headings[i]);
return headings;
},
setColumnClasses() {
let classes = {};
this.columns.map((key) => classes[key] = key);
return classes;
},
loadRecords(actionType) {
this.$store.dispatch(actionType);
}
},
props: {
tableData: {
type: Array,
required: true
},
columns: {
type: Array,
required: true
},
actionType: {
type: String,
required: true
},
headings: {
type: Array,
required: true
},
...
},
mounted() {
this.loadRecords(this.actionType);
}
You are getting this error message because Vue (when mounted) is expecting that the this.$store is defined, and while it might be within your application, you are not importing it, nor are you mocking it.
Here is your test function code you provided:
const wrapper = shallowMount(MyTable, {
propsData: {
tableData: [
{
"product_id":10826345236,
"name":"T-Shirt"
}
],
columns: ['product_id', 'name'],
headings: ['Product ID', 'Name'],
actionType: 'loadProducts'
}
});
Here is what you need to add:
import store from '../path/to/store.js';
import { createLocalVue, shallowMount } from '#vue/test-utils';
// You will want to create a local Vue instance for testing purposes: https://vue-test-utils.vuejs.org/api/#createlocalvue
const localVue = createLocalVue();
// This tells the local Vue instance to use Vuex for the store mechanism.
localVue.use(Vuex);
const wrapper = shallowMount(MyTable, {
localVue, // Bind the local Vue instance when we shallow-mount the component.
store, // Bind the store so all of the methods are available when invoked.
propsData: {
tableData: [
{
"product_id":10826345236,
"name":"T-Shirt"
}
],
columns: ['product_id', 'name'],
headings: ['Product ID', 'Name'],
actionType: 'loadProducts'
}
});
I created a custom directive and it's working good, but when I run the mocha test for the component where I use this custom directive I receive this warning message [Vue warn]: Failed to resolve directive: scroll-text, tell me please how to fix that
test file:
import { shallowMount } from "#vue/test-utils"
import { scrollText } from "z-common/services"
import ZSourcesList from "./ZSourcesList"
Vue.use(scrollText)
const stubs = [
"z-text-field",
"v-progress-circular",
"v-icon",
"z-btn"
]
describe("ZSourcesList.vue", () => {
const sources = []
for (let i = 0; i < 20; i++) {
sources.push({
field: "source",
// format numbers to get 2 diggit number with leading zero 1 -> 01
value: `cluster-${i.toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false })}`,
__typename: "SuggestV2Result"
})
}
it("displays 'No matching sources found' if there are no sources", () => {
const wrapper = shallowMount(ZSourcesList, {
mocks: {
$apollo: {
queries: {
suggestions: {
loading: false,
},
},
},
},
stubs,
sync: false,
data() {
return {
suggestions: [],
}
},
})
expect(wrapper.find(".notification .z-note")).to.exist
})
})
Try registering your custom directive on a local vue instance and then mounting to that local vue instance.
import { shallowMount, createLocalVue } from "#vue/test-utils"
import { scrollText } from "z-common/services"
import ZSourcesList from "./ZSourcesList"
const localVue = createLocalVue()
localVue.use(scrollText) // Register the plugin to local vue
const stubs = [
"z-text-field",
"v-progress-circular",
"v-icon",
"z-btn"
]
describe("ZSourcesList.vue", () => {
const sources = []
for (let i = 0; i < 20; i++) {
sources.push({
field: "source",
// format numbers to get 2 diggit number with leading zero 1 -> 01
value: `cluster-${i.toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false })}`,
__typename: "SuggestV2Result"
})
}
it("displays 'No matching sources found' if there are no sources", () => {
const wrapper = shallowMount(ZSourcesList, {
mocks: {
$apollo: {
queries: {
suggestions: {
loading: false,
},
},
},
},
localVue, // Mount this component to localVue
stubs,
sync: false,
data() {
return {
suggestions: [],
}
},
})
expect(wrapper.find(".notification .z-note")).to.exist
})
})
Using a local vue instance instead of the global in test cases will also prevent polluting the global vue instance and help to prevent side effects in other test cases.
I'm using Bootstrap vue table with contentful's API and could use some help with my code. I'm attempting to use a for loop to iterate over an array and get the property values. The console.info(episodes); call prints out each iteration for the var episodes, but now how do I bind this to my variable episodes. Using return only returns one result even outside of the for each loop. Any help or suggestions on another implementation is greatly appreciated. Full Template below.
<template>
<div>
<h1>Bootstrap Table</h1>
<b-table striped responsive hover :items="episodes" :fields="fields"></b-table>
</div>
</template>
<style>
</style>
<script>
import axios from "axios";
// Config
import config from "config";
// Vuex
import store from "store";
import { mapGetters, mapActions } from "vuex";
// Services
import { formatEntry } from "services/contentful";
// Models
import { entryTypes } from "models/contentful";
// UI
import UiEntry from "ui/Entry";
import UiLatestEntries from "ui/LatestEntries";
const contentful = require("contentful");
const client = contentful.createClient({
space: "xxxx",
environment: "staging", // defaults to 'master' if not set
accessToken: "xxxx"
});
export default {
name: "contentful-table",
data() {
return {
fields: [
{
key: "category",
sortable: true
},
{
key: "episode_name",
sortable: true
},
{
key: "episode_acronym",
sortable: true
},
{
key: "version",
sortable: true
}
],
episodes: []
};
},
mounted() {
return Promise.all([
// fetch the owner of the blog
client.getEntries({
content_type: "entryWebinar",
select: "fields.title,fields.description,fields.body,fields.splash"
})
])
.then(response => {
// console.info(response[0].items);
return response[0].items;
})
.then(response => {
this.episodes = function() {
var arrayLength = response.length;
var episodes = [];
for (let i = 0; i < arrayLength; i++) {
// console.info(response[i].fields.title + response[i].fields.splash + response[i].fields.description + response[i].fields.body );
var episodes = [
{
category: response[i].fields.title,
episode_name: response[i].fields.splash,
episode_acronym: response[i].fields.description,
version: response[i].fields.body
}
];
// episodes.forEach(category => episodes.push(category));
console.info(episodes);
}
return episodes;
};
})
.catch(console.error);
}
};
</script>
You can use the map method on the response array to return all the elements.
In your current example you keep re-setting the episodes variable, instead of the push() you actually want to do. The map method is still a more elegant way to solve your problem.
this.episodes = response.map((item) => {
return {
category: item.fields.title,
episode_name: items.fields.splash,
episode_acronym: item.fields.description,
version: item.fields.body
}
})
You can update the last then to match the last then below
]).then(response => {
return response[0].items;
})
.then((response) => {
this.episodes = response.map((item) => {
return {
category: item.fields.title,
episode_name: items.fields.splash,
episode_acronym: item.fields.description,
version: item.fields.body
};
});
})
.catch(console.error)
You do have an unnecessary second then, but I left it there so that you could see what I am replacing.
I want to create a tree in VS code, but my problem is how to manually add a node to my tree. I am not sure from where to start. I tried to review all the projects that created a tree for VScode as an extension.
My problem is that I am not an expert in Typescript and the examples are not so clear or I am not sure how it is working.
Would you mind helping me to understand how to create the tree in VS code? My problem is with creating a node and then adding the node to tree.
I reviewed these projects:
vscode-code-outline
vscode-extension-samples
vscode-git-tree-compare
vscode-html-languageserver-bin
vscode-mock-debug
vscode-tree-view
Update1:
I managed to use "vscode-extension-samples" and generate the below code examples; now I don't know what I should do, or in other words, how to fill the tree. I tried to use mytree class to fill the data but it didn't work. Would you mind advising me what is next?
extension.ts
'use strict';
import * as vscode from 'vscode';
import { DepNodeProvider } from './nodeDependencies'
import { JsonOutlineProvider } from './jsonOutline'
import { FtpExplorer } from './ftpExplorer.textDocumentContentProvider'
import { FileExplorer } from './fileExplorer';
//mycode
import { SCCExplorer } from './sccExplorer';
export function activate(context: vscode.ExtensionContext) {
// Complete Tree View Sample
new FtpExplorer(context);
new FileExplorer(context);
//mycode
new SCCExplorer(context);
// Following are just data provider samples
const rootPath = vscode.workspace.rootPath;
const nodeDependenciesProvider = new DepNodeProvider(rootPath);
const jsonOutlineProvider = new JsonOutlineProvider(context);
vscode.window.registerTreeDataProvider('nodeDependencies', nodeDependenciesProvider);
vscode.commands.registerCommand('nodeDependencies.refreshEntry', () => nodeDependenciesProvider.refresh());
vscode.commands.registerCommand('nodeDependencies.addEntry', node => vscode.window.showInformationMessage('Successfully called add entry'));
vscode.commands.registerCommand('nodeDependencies.deleteEntry', node => vscode.window.showInformationMessage('Successfully called delete entry'));
vscode.commands.registerCommand('extension.openPackageOnNpm', moduleName => vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(`https://www.npmjs.com/package/${moduleName}`)));
vscode.window.registerTreeDataProvider('jsonOutline', jsonOutlineProvider);
vscode.commands.registerCommand('jsonOutline.refresh', () => jsonOutlineProvider.refresh());
vscode.commands.registerCommand('jsonOutline.refreshNode', offset => jsonOutlineProvider.refresh(offset));
vscode.commands.registerCommand('jsonOutline.renameNode', offset => jsonOutlineProvider.rename(offset));
vscode.commands.registerCommand('extension.openJsonSelection', range => jsonOutlineProvider.select(range));
}
sccExplorer.ts
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import * as mkdirp from 'mkdirp';
import * as rimraf from 'rimraf';
//#region Utilities
interface Entry {
uri: vscode.Uri,
type: vscode.FileType
}
//#endregion
export class FileSystemProvider implements vscode.TreeDataProvider<Entry> {
getTreeItem(element: Entry): vscode.TreeItem | Thenable<vscode.TreeItem> {
throw new Error("Method not implemented.");
}
onDidChangeTreeData?: vscode.Event<Entry>;
getChildren(element?: Entry): vscode.ProviderResult<Entry[]> {
throw new Error("Method not implemented.");
}
getParent?(element: Entry): vscode.ProviderResult<Entry> {
throw new Error("Method not implemented.");
}
private _onDidChangeFile: vscode.EventEmitter<vscode.FileChangeEvent[]>;
constructor() {
this._onDidChangeFile = new vscode.EventEmitter<vscode.FileChangeEvent[]>();
}
}
export class SCCExplorer {
private fileExplorer: vscode.TreeView<any>;
constructor(context: vscode.ExtensionContext) {
const treeDataProvider = new myTree().directories;
this.fileExplorer = vscode.window.createTreeView('scc_Explorer', { treeDataProvider });
vscode.commands.registerCommand('scc_Explorer.openFile', (resource) => this.openResource(resource));
}
private openResource(resource: vscode.Uri): void {
vscode.window.showTextDocument(resource);
}
}
export class myTree{
directories: any;
constructor()
{
this.directories = [
{
name: 'parent1',
child: [{
name: 'child1',
child: []
},
{
name: 'child2',
child: []
}]
},
{
name: 'parent2',
child: {
name: 'child1',
child: []
}
},
{
name: 'parent2',
child: [{
name: 'child1',
child: []
},
{
name: 'child2',
child: []
}]
}];
}
}
I finally got it working. It took me very long and I had it right all the time. My issue was I never did explicitly expand the items, so I would never see nested results and only the top level.
Basic working example
import * as vscode from "vscode";
export class OutlineProvider
implements vscode.TreeDataProvider<any> {
constructor(private outline: any) {
console.log(outline);
}
getTreeItem(item: any): vscode.TreeItem {
return new vscode.TreeItem(
item.label,
item.children.length > 0
? vscode.TreeItemCollapsibleState.Expanded
: vscode.TreeItemCollapsibleState.None
);
}
getChildren(element?: any): Thenable<[]> {
if (element) {
return Promise.resolve(element.children);
} else {
return Promise.resolve(this.outline);
}
}
}
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand(
"outliner.outline",
async () => {
vscode.window.registerTreeDataProvider(
"documentOutline",
new OutlineProvider([dataObject])
);
}
);
context.subscriptions.push(disposable);
}
const dataObject = {
label: "level one",
children: [
{
label: "level two a",
children: [
{
label: "level three",
children: [],
},
],
},
{
label: "level two b",
children: [],
},
],
}
And of course in package.json
"contributes": {
"commands": [
{
"command": "outliner.outline",
"title": "Outline"
}
],
"views": {
"explorer": [
{
"id": "documentOutline",
"name": "Document Outline"
}
]
}
},
Types
note the type for treeDataProvider is not neccecarly what you return. Only the getTree item has to return a tree item or a class that extends it.
interface CustomType {
label: string
children?: CustomType[]
}
export class TypeExample
implements vscode.TreeDataProvider<CustomType> {
constructor(private data: CustomType[]) { }
getTreeItem(element: CustomType): vscode.TreeItem {
return new vscode.TreeItem(
element.label,
(element.children?.length ?? 0) > 0
? vscode.TreeItemCollapsibleState.Expanded
: vscode.TreeItemCollapsibleState.None
);
}
getChildren(element?: CustomType): Thenable<CustomType[]> {
return element && Promise.resolve(element.children ?? [])
|| Promise.resolve(this.data);
}
}
I thought at first the type of the data provider should be the return type of the tree item, this doesnt make much sense of course and I was trying to wrap my head around the reasoning. Now I understand that you pass your custom type in and all other methods inherit this type and expect this type as its argument. Only the getTreeItem method has to return a valid tree item that can be rendered.