Related
I'm writing a small CLI in typescript and I have a command which basically allows me to generate a json file with default values in it (just like npm init -y), but I don't know how to auto answer the questions in inquirer.
This is what I've got so far:
export const initializeConfig = (project: string, ...args: boolean[]) => {
prompt([
{
type: "input",
name: "name",
message: "What is the name of the project?",
default: basename(cwd()),
when: () => args.every((arg) => arg === false),
},
{
type: "list",
name: "project",
message: "What is the type of the project?",
choices: ["Node", "Python"],
default: project,
when: () => args.every((arg) => arg === false),
},
])
.then((answers: Answers) => {
config = setConfig({ name: answers.name });
config = setConfig({ project: answers.project });
})
.then(() =>
prompt([
{
type: "input",
name: "path",
message: "Where is your project root located?",
default: ".",
when: () => args.every((arg) => arg === false),
},
{
type: "input",
name: "ignore",
message: "What do you want to ignore? (comma separated)",
default: defaultIgnores(config.project).ignore,
when: () => args.every((arg) => arg === false),
},
]).then((answers: Answers) => {
config = setConfig(ignoreFiles(config.project, answers.ignore));
createConfig(answers.path, config);
})
);
};
I thought that if I'd skip/hide the questions with when(), it would use the default values, but it doesn't. It's always undefined.
Didn't find this topic on the internet so far. Any ideas?
Kind of a life hack, but I managed to "auto answer" my questions in inquirer by creating a defaults() function that returns an object of the default values.
Then I can use those if my answer object is empty as you see below:
const defaults = (project: string) => {
return {
name: basename(cwd()),
project,
path: ".",
ignore: defaultIgnores(project).ignore,
};
};
export let config: any = {
version,
};
export const initializeConfig = (project: string, ...args: boolean[]) => {
prompt([
{
type: "input",
name: "name",
message: "What is the name of the project?",
default: defaults(project).name,
when: () => args.every((arg) => arg === false),
},
{
type: "list",
name: "project",
message: "What is the type of the project?",
choices: ["Node", "Python"],
default: defaults(project).project,
when: () => args.every((arg) => arg === false),
},
])
.then((answers: Answers) => {
const { name, project: projectName } = defaults(project);
config = setConfig({ name: answers.name || name });
config = setConfig({ project: answers.project || projectName });
})
.then(() =>
prompt([
{
type: "input",
name: "path",
message: "Where is your project root located?",
default: defaults(project).path,
when: () => args.every((arg) => arg === false),
},
{
type: "input",
name: "ignore",
message: "What do you want to ignore? (comma separated)",
default: defaults(project).ignore,
when: () => args.every((arg) => arg === false),
},
]).then((answers: Answers) => {
const { ignore, path } = defaults(project);
config = setConfig(
ignoreFiles(config.project, (answers.ignore || ignore)!)
);
createConfig(answers.path || path, config);
})
);
};
I'm attempting to check if a user's ID is in this array and if they are, also get the "text" from it.
Array:
const staff = [
{
user: '245569534218469376',
text: 'dev'
},
{
user: '294597887919128576',
text: 'loner'
}
];
I've tried if (staff.user.includes(msg.member.id)) (Which I didn't think was going to work, and didn't.)
const findUser = (users, id) => users.find(user => user.id === id)
const usersExample = [
{
id: '123456765',
text: 'sdfsdfsdsd'
},
{
id: '654345676',
text: 'fdgdgdg'
}
]
//////////////////
const user = findUser(usersExample, '123456765')
console.log(user && user.text)
The some method on an array is used to tell if an item meets a condition, it is similar to the find method but the find method returns the item where the some method return true or false.
const staff = [
{
user: '245569534218469376',
text: 'dev'
},
{
user: '294597887919128576',
text: 'loner'
}
];
const isStaff = (staff, id) => staff.some(s => s.user === id);
console.log(isStaff(staff, '123'));
console.log(isStaff(staff, '245569534218469376'));
You may try something like this:
const staff = [
{
user: '245569534218469376',
text: 'dev'
},
{
user: '294597887919128576',
text: 'loner'
}
];
let item = staff.find(item => item.user == '294597887919128576'); // msg.member.id
if (item) {
console.log(item.text);
}
One another way to do that is:
const inArray = (array, id) => array.filter(item => item.user === id).length >= 1;
const users = [
{
user: '245569534218469356',
text: 'foo'
}, {
user: '245564734218469376',
text: 'bar'
}, {
user: '246869534218469376',
text: 'baz'
}
];
console.log(inArray(users, '246869534218469376')); // true
console.log(inArray(users, '222479534218469376')); // false
So I have to make a post request without a form or a button. I have the patientInfo array that is rendered on a table. When the user chooses a location for a patient, then that patient will have a timestamp value. When the patient in the array has a timestamp that's when I am supposed to auto post the patient with the timestamp.
My handleAutoObsSubmit() is kinda working but the problem is, it maps over the patienArray and sends the patient multiple time so if the user chooses the third patient's location, there will be three object of the same patient that is sent.
Another issue I am having with is componentDidUpdate, it sends the post request every second. I suspect that is because the patient count is being count down every sec. Not 100% sure though. Is it even a good idea to send post request in componentDidUpdate?
patientInfo = [
{ count: 100, room: "1", name: 'John Nero', timeStamp: '', location: ''},
{ count: 100, room: "2", name: 'Shawn Michael', timeStamp: '', location: ''},
{ count: 100, room: "3", name: 'Gereth Macneil', timeStamp: '', location: ''}
]
handleAutoObsSubmit = () => {
const postUrl = '/send_patient_that_has_timeStamp';
const timeStampedPatients = this.state.patientInfo.filter(patient => patient.timeStamp !== '');
let data = {};
timeStampedPatients.map((patient) => {
data = {
room: patient.room,
patient: patient.name,
timestamp: patient.timeStamp,
location: patient.locationInfo,
};
});
fetch(postUrl, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then((res) => {
if (!res.ok) {
console.log('request failed');
} else {
console.log('request sent');
}
});
}
componentDidUpdate() {
this.state.patientInfo.map(patient => {
if (patient.timeStamp !== '') {
this.handleAutoObsSubmit();
}
});
}
componentDidMount() {
this.countDownInterval = setInterval(() => {
this.setState(prevState => ({
patientInfo: prevState.patientInfo.map((patient) => {
if (patient.locationInfo!== '') {
if (patient.count <= 0) {
clearInterval(this.countDownInterval);
}
return { ...patient, count: patient.count - 1 };
}
return patient;
})
}));
}, 1000);
}
You should be able to handle it in a similar fashion to this:
function Table() {
const [tableData, setTableData] = React.useState([
{
name: "John Doe",
timestamp: ""
},
{
name: "Jane Doe",
timestamp: ""
},
{
name: "Nancy Doe",
timestamp: ""
}
]);
const updateItem = (event, index) => {
let newstate = [...tableData];
newstate[index].timestamp = (new Date(Date.now())).toString();
alert(`Do POST here: ${JSON.stringify(newstate[index],null,2)}`);
setTableData(newstate);
};
return (
<table border="5">
<tr>
<th>
<div>Patient</div>
</th>
<th>
<div>Timestamp</div>
</th>
<th>Update</th>
</tr>
{tableData.map((item, index) => {
return (
<tr>
<td>{item.name}</td>
<td style={{width:'410px'}}>{item.timestamp}</td>
<td>
<button
style={{backgroundColor:'green', color:'white'}}
onClick={event => updateItem(event, index)}>
UPDATE
</button>
</td>
</tr>
);
})}
</table>
);
}
ReactDOM.render(<Table />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
I am having trouble understanding how to access the data from a local JS file. I have read the React documentation up and down, but I'm stuck on this problem. There must be a flaw in my state/prop logic?
import announcementData from "./AnnouncementData.js"
class Detail extends Component {
constructor(props) {
super(props);
this.state = {
announcement: [
{
id: 0,
...
}
async fetchDetails(id) {
let response = announcementData;
this.state.announcement.map(response, (value, key) => {
this.setState({
[value]: key
}).catch(error => {
this.setState({
error: error.message
});
});
});
}
async componentDidMount() {
const { match } = this.props;
await this.fetchDetails(match.params.id);
}
render() {
const detail = {
id: this.state.announcement.id,
title: this.state.announcement.title,
site_id: this.state.announcement.site_id,
content: this.state.announcement.content,
status: this.state.announcement.status,
scheduled_at: this.state.announcement.scheduled_at,
created_at: this.state.announcement.created_at,
categories: this.state.announcement.categories,
members: this.state.announcement.members
};
return (
<div>
<ListGroup>
<Announcement
id={detail.id}
title={detail.title}
site_id={detail.site_id}
content={detail.content}
status={detail.status}
scheduled_at={detail.scheduled_at}
created_at={detail.created_at}
categories={detail.categories}
members={detail.members}
/>
</ListGroup>
</div>
);
}
}
const Announcement = ({id, title, site_id, content, status, scheduled_at, created_at, categories, members}) => {
return (
<div>
<ListGroupItem>ID: {id}</ListGroupItem>
<ListGroupItem>Title: {title}</ListGroupItem>
<ListGroupItem>Site ID: {site_id}</ListGroupItem>
<ListGroupItem>Content: {content}</ListGroupItem>
<ListGroupItem>Status: {status}</ListGroupItem>
<ListGroupItem>Scheduled at: {scheduled_at}</ListGroupItem>
<ListGroupItem>Created at: {created_at}</ListGroupItem>
<ListGroupItem>Categories: {categories}</ListGroupItem>
<ListGroupItem>Members: {members}</ListGroupItem>
</div>
);
};
export default Detail;
I'm trying to publish the details from an array from a local file (for now) to be displayed by the UI. With this minimal code, I am able to display the "Announcement" function with no data, like so:
ID:
Title:
Site ID:
Content:
Status:
Scheduled at:
Created at:
Categories:
Members:
I need to display the actual data coming from the .js file.
It should be a very basic problem but I am a beginner. Any help is appreciated. Thanks!
AnnouncementData.js:
const announcementData = [
{
id: 0,
title: "John Doe",
site_id: "my business",
content: "I have a new business!",
status: true,
created_at: "14/03/2019",
updated_at: "24/04/2019",
categories: [{ id: 0, name: "John Doe" }],
members: [{ id: 1, name: "Jane Doe", photo_url: "jane.png" }]
},
export default announcementData;
You should change your fetchDetails function to something like this:
async fetchDetails(id) {
this.setState({
announcement: announcementData.find(v => v.id === id)
});
}
I have an angular application and I need to do some unit testing on some methods with Jasmine. IN this case I do a unit test on a select list. So that the select list will not be empty.
The method looks like this:
createStatusOptions(listValueoptions: OptionModel[], resources: any): OptionModel[] {
const processStatusOptions = listValueoptions.map(listValueOption => {
listValueOption.value = `${caseStatusEnum.inProgress}_${listValueOption.value}`;
listValueOption.selected = true;
return listValueOption;
});
const caseStatusEnumKeys = Object.keys(caseStatusEnum).filter(key => !isNaN(Number(key)));
const enumOptions = this.optionService.createOptions(
new ConfigOptionModel({ source: caseStatusEnumKeys, resources, resourcesModel: enumResourcesModel, isCustomEnum: true, }));
return [
this.getEnumOption(enumOptions, caseStatusEnum.submitted, true),
...processStatusOptions,
this.getEnumOption(enumOptions, caseStatusEnum.closed),
];
}
private getEnumOption(options: OptionModel[], enumType, isSelected = false): OptionModel {
const option = options.filter(enumOption => enumOption.value === `${enumType}`)[0];
option.selected = isSelected;
return option;
}
And I have the unit test like this:
it('should create status options when there ar list value options are provided', () => {
optionService.options = [
{
value: caseStatusEnum.submitted.toString(),
},
{
value: caseStatusEnum.inProgress.toString(),
},
{
value: caseStatusEnum.closed.toString(),
},
] as OptionModel[];
// tslint:disable-next-line:max-line-length
const result = service.createStatusOptions(optionService.options, [[103], [104], [105] ]);
console.log(result);
expect(result.length).toBe(2);
expect(result).toEqual([{ value: '103', selected: true }, { value: '105', selected: false }]);
});
But I get an error like this:
Services: CaseService > should create status options when there ar list value options are provided
TypeError: Cannot set property 'selected' of undefined
at <Jasmine>
at CaseService.getEnumOption (http://localhost:9878/src/app/case/src/services/case.service.ts?:130:9)
at CaseService.getEnumOption [as createStatusOptions] (http://localhost:9878/src/app/case/src/services/case.service.ts?:109:22)
at UserContext.<anonymous> (http://localhost:9878/src/app/case/src/services/case.service.spec.ts?:149:32)
at ZoneDelegate.../../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/zone.js?:388:1)
at ProxyZoneSpec.push.../../node_modules/zone.js/dist/proxy.js.ProxyZoneSpec.onInvoke (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/proxy.js?:128:1)
at ZoneDelegate.../../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/zone.js?:387:1)
at Zone.../../node_modules/zone.js/dist/zone.js.Zone.run (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/zone.js?:138:1)
at runInTestZone (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/jasmine-patch.js?:145:1)
at UserContext.<anonymous> (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/jasmine-patch.js?:160:1)
at <Jasmine>
So my question is: How to solve this?
Thank you
if I do this:
console.log(optionService.options);
I get this output:
Array(3)
0: {value: "103", selected: true}
1: {value: "104"}
2: {value: "105", selected: false}
length: 3
__proto__: Array(0)
this is the file:
import { fakeAsync, tick } from '#angular/core/testing';
import { FormServiceMock, MultiFileUploadServiceMock } from 'afw/forms/testing';
import { AfwHttp } from 'afw/generic-services';
import { AfwHttpMock, OptionServiceMock } from 'afw/generic-services/testing';
import { OptionModel, SearchResultModel } from 'afw/models';
import { FeedbackStoreServiceMock } from 'afw/store-services/testing';
import { RouterMock } from 'afw/testing';
import { PagingDataModel, TableSortDataModel } from 'afw/ui-components';
import { caseOwnerEnum, caseStatusEnum, caseTypeEnum, MultiFileUploadResourcesModel } from 'lr/models';
import { Observable, observable } from 'rxjs';
import { CaseTypeInfoModel } from 'support-shared/base/models';
import { CaseTypeInfoStoreServiceMock } from 'support-shared/base/services/case-type-info-store.service.mock';
import { CaseFormComponent } from '../case-base/src/case-form/case-form.component';
import { CaseBaseModel, CaseReferenceModel } from '../models';
import { CaseService } from './case.service';
let service: CaseService;
let afwHttpMock: AfwHttpMock;
// tslint:disable-next-line:prefer-const
let formServiceMock: FormServiceMock;
let multiFileUploadService: MultiFileUploadServiceMock;
let router: RouterMock;
let feedbackStoreService: FeedbackStoreServiceMock;
let optionService: OptionServiceMock;
let caseTypeInfoStoreService: CaseTypeInfoStoreServiceMock;
// tslint:disable-next-line:prefer-const
let component: CaseFormComponent;
fdescribe('Services: CaseService', () => {
beforeEach(() => {
afwHttpMock = new AfwHttpMock();
multiFileUploadService = new MultiFileUploadServiceMock();
router = new RouterMock();
feedbackStoreService = new FeedbackStoreServiceMock();
optionService = new OptionServiceMock();
caseTypeInfoStoreService = new CaseTypeInfoStoreServiceMock();
service = new CaseService(afwHttpMock as any, multiFileUploadService as any, router as any,
feedbackStoreService as any, optionService as any, caseTypeInfoStoreService as any);
});
it('should create an instance', () => {
expect(service).toBeTruthy();
});
it('should get case reference details', () => {
afwHttpMock.setupOnlyResponse({ type: caseTypeEnum.revisionRequest, details: { bsn: 'bsnLabel' } }, 200);
const d = service.getCaseReferenceDetails('spinnerMessage', { reference: '112314121', type: caseTypeEnum.revisionRequest });
d.subscribe(r => {
expect(r.details.length === 1);
expect(r.details[0].key).toBe('bsn');
expect(r.details[0].value).toBe('bsnLabel');
expect((r.details[0] as any).resourceKey).toBe('bsn');
});
afwHttpMock.returnSuccessResponse();
});
// tslint:disable-next-line:no-identical-functions
it('should get case reference details with full response', () => {
afwHttpMock.setupOnlyResponse({ body: { type: caseTypeEnum.revisionRequest, details: [{ key: 'hoi' }] } }, 200);
const d = service.getCaseReferenceDetailsFullResponse('spinnerMessage', { reference: '100001075', type: caseTypeEnum.revisionRequest });
// tslint:disable-next-line:no-commented-code
// tslint:disable-next-line:no-identical-functions
/* let result;
d.subscribe(r => {
result = r;
}); */
d.subscribe(r => {
expect(r.ok === true);
expect(r.body.details[0].key).toBe('hoi');
});
afwHttpMock.returnSuccessResponse();
// expect(result.ok === true);
// expect(result.)
});
// tslint:disable-next-line:no-commented-code
it('shoud get case type info configuration that is used on various views when snapshot exists', () => {
let result99: Observable<CaseTypeInfoModel[]>;
result99 = service.getCaseTypeInfo('spinner') as Observable<CaseTypeInfoModel[]>;
const response = [{ mock: 'mock' } as any];
service['caseTypeInfoSnapshot'] = response;
service.getCaseTypeInfo('spinner').subscribe(i => {
expect(i).toEqual(response);
});
});
// tslint:disable-next-line:no-identical-functions
it('shoud get case type info configuration that is used on various views when snapshot doesnt exists', () => {
let result99: Observable<CaseTypeInfoModel[]>;
const spy = spyOn(caseTypeInfoStoreService, 'addCaseTypeInfoToStore');
result99 = service.getCaseTypeInfo('spinner') as Observable<CaseTypeInfoModel[]>;
const response = [{ mock: 'mock' } as any];
service['caseTypeInfoSnapshot'] = response;
// caseTypeInfoStoreService..subscribe((result) => { expect(result).toBe(false); });
result99.subscribe((result) => {
expect(response).toEqual(response);
});
afwHttpMock.setupOnlyResponse(result99, 200);
afwHttpMock.returnSuccessResponse();
});
it('should create status options when no list value options are provided', () => {
optionService.options = [
{
value: caseStatusEnum.submitted.toString(),
},
{
value: caseStatusEnum.inProgress.toString(),
},
{
value: caseStatusEnum.closed.toString(),
},
] as OptionModel[];
// tslint:disable-next-line:no-commented-code
// const spy = spyOn(service, 'createStatusOptions');
const result = service.createStatusOptions([], {});
expect(result.length).toBe(2);
expect(result).toEqual([{ value: '103', selected: true }, { value: '105', selected: false }]);
// tslint:disable-next-line:no-commented-code
// const response = [{ mock: 'mock' } as any];
// expect(spy).toBe(result);
});
it('should create status options when there ar list value options are provided', () => {
optionService.options = [
{
value: caseStatusEnum.submitted.toString(),
},
{
value: caseStatusEnum.inProgress.toString(),
},
{
value: caseStatusEnum.closed.toString(),
},
] as OptionModel[];
// tslint:disable-next-line:max-line-length
const result = service.createStatusOptions(optionService.options, 103);
console.log(optionService.options);
expect(result.length).toBe(2);
expect(result).toEqual([{ value: '103', selected: true }, { value: '105', selected: false }]);
});
it('should get case reference without details', () => {
afwHttpMock.setupOnlyResponse({}, 200);
const spy = spyOn(afwHttpMock, 'post').and.callThrough();
const model = new CaseReferenceModel({ reference: '112314121', type: caseTypeEnum.revisionRequest });
const d = service.getCaseReferenceDetails('spinnerMessage', model);
d.subscribe(r => {
expect(r).toBeDefined();
});
expect(spy).toHaveBeenCalledWith('api/support/cases/get-reference-details', model, 'spinnerMessage');
afwHttpMock.returnSuccessResponse();
});
it('should add case reference without details', () => {
afwHttpMock.setupOnlyResponse({}, 200);
const spy = spyOn(afwHttpMock, 'post').and.callThrough();
const model = new CaseReferenceModel({ reference: '112314121', type: caseTypeEnum.revisionRequest });
const d = service.addCase('spinnerMessage', model as any);
d.subscribe(r => {
expect(r).toBeDefined();
});
expect(spy).toHaveBeenCalledWith('api/support/cases', model, 'spinnerMessage');
afwHttpMock.returnSuccessResponse();
});
it('should search for cases', () => {
const formModel: any = { makeQueryString: () => 'name=test' };
const pagingModel = new PagingDataModel({ currentPage: 10, itemsPerPage: 20 });
const sortModel = new TableSortDataModel({ columnName: 'kol', isDescending: false });
const spy = spyOn(afwHttpMock, 'get').and.callThrough();
const mockData = [
new CaseBaseModel({
id: 100000001,
type: caseTypeEnum.revisionRequest,
status: caseStatusEnum.inProgress,
substatus: 5266,
verdict: null,
owner: caseOwnerEnum.caseManager,
dateSubmitted: '02-02-2009',
dateClosed: '',
reference: 'aaa',
}),
];
const setupResponse = new SearchResultModel<CaseBaseModel>();
setupResponse.result = mockData;
setupResponse.totalResultCount = 27;
afwHttpMock.setupOnlyResponse(setupResponse, 200);
let response: SearchResultModel<CaseBaseModel>;
service.search(formModel, sortModel, pagingModel, 'spinnerText').subscribe(result => {
response = result;
});
afwHttpMock.returnOnlyResponse();
expect(spy).toHaveBeenCalledWith('api/support/cases?name=test&columnName=kol&isDescending=false¤tPage=10&itemsPerPage=20',
'spinnerText');
expect(response).toEqual(setupResponse);
expect(response.result[0].getResourceForStatus).toBeDefined();
});
it('should save documents', fakeAsync(() => {
const spy = spyOn(multiFileUploadService, 'syncFilesWithBackend').and.callThrough();
const spyRouter = spyOn(router, 'navigate').and.callThrough();
const spyFeedback = spyOn(feedbackStoreService, 'addSuccessMessageOnMainPortal');
service.saveDocuments(1, [{} as any], MultiFileUploadResourcesModel.keys, '../', { key: 'da', value: 'fa' });
expect(spy).toHaveBeenCalledWith('api/support/cases/1/documents', [{}],
MultiFileUploadResourcesModel.keys.bijlageToevoegenSpinnerTekst,
MultiFileUploadResourcesModel.keys.bijlageVerwijderenSpinnerTekst
);
tick();
expect(spyRouter).toHaveBeenCalledWith(['../']);
expect(spyFeedback).toHaveBeenCalled();
}));
it('should not save documents if there are no documents in array', fakeAsync(() => {
const spy = spyOn(multiFileUploadService, 'syncFilesWithBackend').and.callThrough();
const spyRouter = spyOn(router, 'navigate').and.callThrough();
const spyFeedback = spyOn(feedbackStoreService, 'addSuccessMessageOnMainPortal');
service.saveDocuments(1, [], MultiFileUploadResourcesModel.keys, '../', { key: 'da', value: 'fa' });
expect(spy).not.toHaveBeenCalled();
tick();
expect(spyRouter).toHaveBeenCalledWith(['../']);
expect(spyFeedback).toHaveBeenCalled();
}));
it('should save documents and report errors', fakeAsync(() => {
multiFileUploadService.setResponse([{}, { error: {} }]);
spyOn(multiFileUploadService, 'makeWarningMessageForUnsyncedFiles').and.returnValue('mock');
const spyRouter = spyOn(router, 'navigate').and.callThrough();
const spyFeedback = spyOn(feedbackStoreService, 'addWarningMessageOnMainPortal');
const spy = spyOn(multiFileUploadService, 'syncFilesWithBackend').and.callThrough();
service.saveDocuments(1, [{} as any], MultiFileUploadResourcesModel.keys, '../', { key: 'da', value: 'fa' });
expect(spy).toHaveBeenCalledWith('api/support/cases/1/documents', [{}],
MultiFileUploadResourcesModel.keys.bijlageToevoegenSpinnerTekst,
MultiFileUploadResourcesModel.keys.bijlageVerwijderenSpinnerTekst
);
tick();
expect(spyRouter).toHaveBeenCalledWith(['../']);
expect(spyFeedback).toHaveBeenCalled();
}));
it('should get case by id', () => {
const id = 66208014;
const setupResponse = new CaseBaseModel({
id,
dateSubmitted: '',
owner: caseOwnerEnum.caseManager,
reference: 'ksjhkjshdf',
status: caseStatusEnum.submitted,
type: caseTypeEnum.revisionRequest,
});
afwHttpMock.setupOnlyResponse(setupResponse, 200);
service.getCase(id, 'spinner').subscribe(r => {
expect(r).toEqual(setupResponse);
});
afwHttpMock.returnSuccessResponse();
});
it('edit the case with model', () => {
const spy = spyOn(service, 'editCase').and.callThrough();
const caseUpdate = new CaseBaseModel({
id: 100001075,
dateSubmitted: '',
owner: caseOwnerEnum.caseManager,
reference: 'ksjhkjshdf',
status: caseStatusEnum.submitted,
type: caseTypeEnum.revisionRequest,
});
service.editCase('spinner', caseUpdate);
expect(spy).toHaveBeenCalledWith('spinner', caseUpdate);
expect(caseUpdate.id).toEqual(100001075);
});
});
Based on what you showed so far, my guess is that the options parameter passed to getEnumOption() is undefined, which is causing the error you see. A quick console.log(options) within getEnumOption() would verify this.
If your code is working fine otherwise, but only failing in the test then I would make a second guess that you haven't properly mocked/spiedOn this.optionService.createOptions() since it sets up the options parameter that is potentially undefined. That would have been done earlier in the .spec file - if you post the whole file then that would help others who read your question to determine if this is the case.
Update with Stackblitz
I put all your code into a Stackblitz to test it. There was a lot of code I didn't have access to that I just guessed at the functionality of. However, I did discover a few things.
First, when you are testing you appear to be using the same variable both for the mock of the return expected by this.optionService.createOptions() as well as in the call to service.createStatusOptions() - which is likely not what you want to do.
Here is the code snippet I am talking about:
optionService.options = [
{
value: caseStatusEnum.submitted.toString(),
},
{
value: caseStatusEnum.inProgress.toString(),
},
{
value: caseStatusEnum.closed.toString(),
},
] as OptionModel[];
// tslint:disable-next-line:max-line-length
const result = service.createStatusOptions(optionService.options, [[103], [104], [105] ]);
When I called it this way in the Stackblitz I ran into a mutability issue - you are changing the data within the members of the objects inside the array, which will change it whereever that variable is accessed. To overcome this in the Stackblitz I made two copies of the data, one to use in the mock returnValue and another completely separate array of objects for the call to service.createStatusOptions(). Also, I am not familiar with the way you are mocking your service call, so I replaced it with a simple Jasmine spy in the Stackblitz.
Feel free to have a look at what I produced. Perhaps it will be helpful.