const onSubmitClick = async () => {
var { isSuccess, result } = await callDispatch();
if (isSuccess) {
setValidStatus(true);
}
};
async function callDispatch() {
const result = call to server;
let isSuccess = result.success || (result.response && result.response.data.success);
return { isSuccess, result };
}
and in my test file
import { EnterPin } from '../pages/enter-pin';
jest.spyOn(EnterPin.prototype, 'callDispatch').mockImplementation(() =>{
return 'true'
})
var button = screen.getByRole('button');
fireEvent.click(button);
but i am getting Cannot spyOn on a primitive value; undefined given
I tried below too but it didnot work
jest.spyOn(EnterPin.prototype, 'callDispatch').mockImplementation(() =>{
return 'true'
})
var button = screen.getByRole('button');
fireEvent.click(button);
Related
How could I improve this method of rendering only when both variables are met as true, to allow the renderFilters() method to be called:
These two variables are filled asynchronously through 2 API methods:
//getManager()
this.isLoadingManager = true;
//getPdiPOrganization()
this.isLoadingPdiOrganization = true;
promiseRender() {
let interval = setInterval(() => {
if (this.isLoadingManager && this.isLoadingPdiOrganization) {
clearInterval(interval);
this.renderFilters();
} else {
setTimeout(() => {
clearInterval(interval);
this.renderFilters();
}, 5000)
}
}, 500);
}
The problem is that it's very slow... it's calling long after the APIs are called...
Maybe some feature of angular itself, if anyone has a better solution...
const observable = forkJoin({
loading1:this.isLoadingManager,
loading2:this.isLoadingPdiOrganization
});
observable.subscribe({
next: (results) => {
const obs1Val = results[0];
const obs2Val = results[1];
if (obs1Val && obs2Val) {
this.renderFilters();
}
}
})
Or:
const myObservable = Observable.of(this.isLoadingManager && this.isLoadingPdiOrganization);
const myObserver = {
next: (result: Boolean) => this.renderFilters(),
};
myObserver.next(true);
myObservable.subscribe(myObserver);
Adding the methods:
getManager() {
if (this.fromAdminPage && localStorage.getItem('_receivers_pdi')) {
this.meetingService.getIsManager()
.subscribe(res => {
this.showPdiToastNotification = res;
this.isLoadingManager = true;
});
}
}
getPdiPOrganization() {
const url = this.publicEndpoint ? 'current/organization/pdi/configuration' : 'api/current/organization/pdi/configuration';
const requestOptions = {
params: new CustomHttpParams({ isPublicTokenUrl: this.publicEndpoint })
};
this.http.get<any>(url, requestOptions).subscribe(resp => {
this.isLoadingPdiOrganization = true;
this.pdiOrgConfig = resp || {};
this.updatePdiReferenceType(this.pdiOrgConfig);
});
}
You can use forkjoin to subscribe to two observables at the same time. I would stick with using RxJs operators for cases like these. You can read more about forkJoin here.
forkJoin([obs1, obs2]).subscribe({
next: (results) => {
const obs1Val = results[0];
const obs2Val = results[1];
if (obs1Val && obs2Val) {
this.renderFilters();
}
}
});
I'm trying to build a citation generator from json in an API with data about images, stored in key-value pairs. I can get the data to return to the screen, but it always includes undefined in the citation. Sample manifest returns undefined as the creator since that isn't listed in this particular record. How can I keep any undefined value from being returned? I've tried changing the forEach to map, filtering at allMetadata by string length, using if !== undefined at insertCitation, and versions of those in different spots in the code.
EDIT: updated to provide full code, including print to page
(function () {
'use strict';
const buildCitation = {
buildMetadataObject: async function (collAlias, itemID) {
let response = await fetch('/iiif/info/' + collAlias + '/' + itemID + '/manifest.json');
let data = await response.json()
let allMetadata = data.metadata
let citationData = {};
allMetadata.forEach(function (kvpair) {
if (kvpair.value == undefined) {
return false;
} else if (kvpair.label === 'Title') {
citationData.itemTitle = kvpair.value;
} else if (kvpair.label === 'Creator') {
citationData.itemCreator = kvpair.value;
} else if (kvpair.label === 'Repository') {
citationData.itemRepository = kvpair.value;
} else if (kvpair.label === 'Collection Name') {
citationData.itemCollection = kvpair.value;
} else if (kvpair.label === 'Owning Institution') {
citationData.itemOwning = kvpair.value;
} else if (kvpair.label === 'Date') {
citationData.itemDate = kvpair.value;
} else if (kvpair.label === 'Storage Location') {
citationData.itemStorage = kvpair.value;
}
return true;
});
return citationData;
},
insertCitation: function (data) {
var testTitle = data.itemTitle;
console.log(testTitle);
const itemCite = `Citation: "${data.itemTitle}," ${data.itemDate}, ${data.itemCreator}, ${data.itemCollection}, ${data.itemOwning}, ${data.itemStorage}, ${data.itemRepository}.`;
const citationContainer = document.createElement('div');
citationContainer.id = 'citation';
citationContainer.innerHTML = itemCite;
// CHANGED to innerHTML instead of innerText because you may want to format it at some point as HTML code.
if (testTitle) {
document.querySelector('.ItemView-itemViewContainer').appendChild(citationContainer);
}
}
}
document.addEventListener('cdm-item-page:ready', async function (e) {
const citationData = await buildCitation.buildMetadataObject(e.detail.collectionId, e.detail.itemId);
console.log({ citationData });
buildCitation.insertCitation(citationData);
});
document.addEventListener('cdm-item-page:update', async function (e) {
document.getElementById('citation').remove();
const citationData = await buildCitation.buildMetadataObject(e.detail.collectionId, e.detail.itemId);
console.log({ citationData });
buildCitation.insertCitation(citationData);
});
})();
I've simplified your program. The undefined is coming from the fact that there is no item with label Date
const mappings = {
Date: 'itemDate',
Title: 'itemTitle',
Creator: 'itemCreator',
Repository: 'itemRepository',
'Storage Location': 'itemStorage',
'Owning Institution': 'itemOwning',
'Collection Name': 'itemCollection',
}
async function buildMetadataObject(collAlias, itemID) {
let response = await fetch('https://teva.contentdm.oclc.org/iiif/info/p15138coll25/1421/manifest.json');
let data = await response.json()
return data.metadata.reduce(
(acc, { label, value }) => ({ ...acc, [ mappings[label] ]: value }),
{}
)
}
function insertCitation(data) {
var testTitle = data.itemTitle;
const fieldBlackList = ['itemTitle'];
const itemCite = `Citation: "${data.itemTitle}," ${
Object.values(mappings).reduce((acc, cur) => {
if (fieldBlackList.includes(cur)) return acc;
const value = data[cur];
return value ? [...acc, value] : acc
}, []).join(', ')
}.`;
console.log(itemCite);
}
//MAIN PROGRAM
(async() => {
const citationData = await buildMetadataObject();
insertCitation(citationData);
})()
Need help passing data "locationpos"= index of my Locations[] from function to class. I'm very new to React and I'm not sure what I'm doing wrong.
ERROR
Failed to compile
./src/components/data.js
Line 20:30: 'locationpos' is not defined no-undef
Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed.
class Data {
constructor(locationpos) {
this.locationpos=locationpos;
this.updateData();
}
getTimes(date = null) {
date = date === null ? moment().format('DD/MM/YYYY') : date;
var data = this.getData();
return data ? data[date] : [];
}
getSpeadsheetUrl() {
return config.myData[locationpos];
}
function Daily({ locationProps = 1, root }) {
const context = useContext(ThemeContext);
const localization = useCallback(() => {
if (root && cookies.get("location") !== undefined) {
return cookies.get("location");
}
return locationProps;
}, [locationProps, root]);
const [locationState] = useState(localization());
const handleClick = event => {
window.focus();
notification.close(event.target.tag);
};
const openNav = () => {
document.getElementById("sidenav").style.width = "100%";
};
const closeNav = e => {
e.preventDefault();
document.getElementById("sidenav").style.width = "0";
};
// eslint-disable-next-line
const locationpos = locations.indexOf(locations[locationState]);
const _data = useRef(new Data(locationpos));
const getTimes = () => _data.current.getTimes();
Inside your data class, you need to use the instance variable as this.locationPos
getSpeadsheetUrl() {
return config.myData[this.locationpos];
}
Hi i want to return the promise that gets resolved when the first poll finishes...
I have a start_polling method and i want to modify it such that it returns a promise that gets resolved when the items_promise gets resolved...i am not sure how to do it.
What i have tried?
i have created a promise in start_polling method that gets resolved when the item_promise_finish() is executed in then method of items_promise.
Once this promise in start_polling is resolved then i call handle_location method.
It works fine but sometimes i get error cannot read property then of undefined.
How can i fix it.
below is the code,
componentDidUpdate(prevProps, prevState) {
const {state, props} = this;
const current_id = props.item && props.item.id;
const prev_id = prevProps.item && prevProps.item.id;
if (current_id !== prev_id) {
this.stop_polling();
this.setState(this.get_initial_state(), () => {
this.start_polling();
});
} else {
const prev_poll = this.should_poll(prevProps, prevState);
const next_poll = this.should_poll(props, state);
if (prev_poll !== next_poll) {
if (next_poll) {
this.start_polling();
} else {
this.stop_polling();
}
}
if (this.props.location.search) {
this.start_polling().then(() => {
this.handle_location();
})
}
start_polling = () => {
if (this.should_poll(this.props, this.state)) {
this.poll();
return new Promise((resolve) => {
this.item_promise_finish=resolve;
});
}
};
poll = () => {
let still_polling = true;
if (this.cancel_poll_request) {
this.cancel_poll_request();
}
});
const items_promise = client.get_items(this.props.item.id,
cancel_poll_promise);
items_promise.then((request) => {
const next_items = [];
let something_changed = false;
for (const new_item of request.response) {
const old_item = this.state.items.find(
old_item =>
old_item.id === new_item.id);
if (old_item) {
next_items.push(old_item);
} else {
something_changed = true;
next_items.push(new_item);
}
}
if (something_changed) {
const next_state = {items: next_items};
this.setState(next_state);
}
}).then(() => {
if (still_polling) {
this.poll_timeout = setTimeout(this.poll, 100s);
}
this.item_promise_finish();
}).catch(this.props.notifications.request_error);
};
Could someone let me know where i am going wrong or what to be done to fix this. thanks.
I have module executer that will be executed on every api request now i am trying to write cases to unit test that executer. I have promise that returns chain that is being executed based on response. I see issue executing promise in test case , any help here to proper test this use case will be apprecaited.
main.ts
export class Executor {
private passedParam: ILogParams = {} as ILogParams;
constructor(public identity: Identity) {
this._ajv = new Ajv();
}
public execute(moduleName: string): (param1, param2) => any {
const self = this;
// getting rid of the tslint issue with Function
return function(params: any, responseCallback: (param: any , param2: any) => any) {
let _mod;
let _httpRequest;
let _params;
Promise.resolve(getApiModule(self.identity, moduleName))
.then((mod: ModuleBase<any, any>) => {
_mod = mod;
mod.ExecStage = ExecStage.Init;
return mod.init(getHttpModule(self.identity), params);
})
.then((httpRequest: HttpRequestBase) => {
_httpRequest = httpRequest;
if (_mod.Response().Summary.Header) {
throw _mod.Response().Summary;
}
return httpRequest;
})
.then(() => {
// empty the error stack
_mod.objErrorHandler.RemoveAllError();
_mod.ExecStage = ExecStage.Before;
return _mod.before(params);
})
.then((params1: any) => {
const _validators = _mod.getValidators();
let _failed: boolean = false;
return params1;
})
.then((params2: any) => {
_params = params2;
_mod.ExecStage = ExecStage.Core;
return _mod.core(_params, _httpRequest);
})
.catch((data: any) => {
const error: IHeader = {} as IHeader;
})
.then((data: any) => {
responseCallback(data, moduleName.substr(moduleName.indexOf('/') + 1));
});
};
}
}
main.spec.ts
import * as sinon from "sinon";
import {ModuleExecutor} from "./main.ts";
import {ExecStage, Identity} from "../../src/ts/common/Enums";
import ValidateRequestSchema from "../../src/ts/validation/requestSchema.js";
describe("ModuleExecuter", () => {
const sandbox = sinon.createSandbox();
afterEach(function afterTests() {
sandbox.restore();
});
let executer;
let executerSpy;
let results;
let stubbedExecutor;
let apiModule;
let _this;
const stubbedExecutorReturnFuction = sandbox.spy(function(args) {
executer = new ModuleExecutor(Identity.node);
executerSpy = executer.execute();
_this = this;
return new Promise(function(resolve) {
// moduleExecutor.execute(params, callback function)
executerSpy(args, function(data) {
resolve(data.Details);
});
});
});
const stubbedExecutorReturn = sandbox.spy(function(args, innerFunc) {
return innerFunc({Details: successResponse});
});
beforeEach(function() {
stubbedExecutor = sandbox.stub(ModuleExecutor.prototype, "execute").callsFake(function() {
return stubbedExecutorReturn;
});
apiModule = new GetAccountBalance();
const execute = sandbox.spy(stubbedExecutorReturnFuction);
results = execute("Payments/accountBalance/GetAccountBalance", {test:"test"});
});
describe("ModuleExecutor", function() {
it('should call ModuleExecutor.execute', function () {
sinon.assert.calledOnce(stubbedExecutor);
});
it('should return a promise', function() {
results.then(function(data) {
expect(data).toBe(successResponse);
});
});
it('should check validate AJV schema', function() {
let _mod;
results.then((mod: ModuleBase<any, any>) => {
_mod = mod;
mod.ExecStage = ExecStage.Before;
const requestSchema = "I" + _mod.__proto__.constructor.name + "Param";
const classSchema = ValidateRequestSchema[requestSchema];
const valid = _this._ajv.validate(classSchema, {test:"test"});
console.log("BOOLEAN>>>>>>>", valid);
expect(valid).toBeTruthy();
});
});
});
});