Angular6 - Jasmin karma unit test Cannot read property of undefined - unit-testing

My ngOnInit() code is the following
ngOnInit() {
this.isProjectEdit = this._sharedData.isProjectEdit;
if (this.isProjectEdit) {
this.projectModel.projectName = this._sharedData.projectDet;
this.projectModel.projectDescription = this._sharedData.projectDesc;
} else if (!this.isProjectEdit) {
this.projectModel.projectName = "";
this.projectModel.projectDescription = "";
}
}
I have created unit test code for the above code.
it("Should eveluate ngOninit", () => {
fixture.componentInstance.isProjectEdit=false;
fixture.componentInstance.projectModel = {
projectName: "Test",
projectId: 0,
projectVisualization: false,
projectDescription: "Test"
};
fixture.detectChanges();
expect( fixture.componentInstance.isProjectEdit).toBe(false);
});
Im getting an error "Cannot read property 'isProjectEdit' of undefined" on running the test.

Related

How to test a viewChild on Angular with Jest - Unit test?

I am having problems trying to test a viewChild on Angular with Jest.
Here my .ts component:
import { MurQueryViewComponent } from '../../shared/components/mur-query-view/mur-query-view.component';
#ViewChild(MurQueryViewComponent) private consultQuery!: MurQueryViewComponent;
This is the method Im trying to test. The method I can not access is applyTransaction
newVolatility() {
this.dialogSrv
.setDialogAction({
component: VolatilityActionComponent,
data: {
actionType: 'Alta',
},
})
.subscribe((res) => {
if (!res) return;
res.attributes.id = res.id;
this.consultQuery.agGrid.api.applyTransaction({
add: [res.attributes],
});
this.dialogSrv.setAlert({ type: 'success', msg: 'message_new_success' });
});
}
Here my .spec.ts:
This is the test that try to prove that previous methos is been call with same arguments:
it('Method newVolatility', () => {
const sonDebugElement = fixture.debugElement.query(By.directive(MurQueryViewComponent));
const sonComponent: MurQueryViewComponent = sonDebugElement.componentInstance;
component['consultQuery'] = sonComponent;
const SpySetItems= jest.spyOn(component['consultQuery'].agGrid.api, 'applyTransaction');
const SpyDialogAlert= jest.spyOn(component['dialogSrv'], 'setAlert');
component['dialogSrv'].setDialogAction = () => {
return of(mockRow);
}
component.newVolatility();
expect(SpySetItems).toBeCalledWith({add: [mockNewRow]});
expect(SpyDialogAlert).toBeCalledWith({ type: 'success', msg: 'message_new_success' });
});
Here the error on terminal:
Anyone could please let me know how to access a viewChild, witch is a whole component and access to its methos?

Unable to write unit test for ngRx Store selector with Observable

This is the first time I am working on Jasmine unit test framework and I am trying to write unit test for the following lines of code in a component in Angular.
this.subscriptions.push(
this.store.select(authSelectors.getAuthError).subscribe((error) =\> {
if (error) {
this.loading = false;
this.utility.showErrorMessage(error);
if (this.loginForm) {
this.loginForm.reset();
} } }) );
Below is the code that I tried
describe('ngOnInit testing', () =\> {
it('Validate form', () =\> {
let mockError = new Observable\<any\>();
const storespy = jasmine.createSpyObj("Store",\['select'\]);
storespy.select.and.callFake((error: string) =\> {
switch(error) {
case authSelectors.getAuthError.toString(): return mockError;
default: return;
} });
if(mockError != null) { expect(utilityServiceSpy.showErrorMessage).toHaveBeenCalled();
} }) })
But this test case is failing with error:
Error: Expected spy UtilityService.showErrorMessage to have been called.
Am I doing anything wrong here?

Jest testing - cannot clear mocks

I have this tests in my nextjs app:
jest.mock('axios');
describe('Contacts', () => {
afterEach(() => {
axios.get.mockClear();
});
it('first test', async () => {
axios.get.mockImplementation((url: string) => {
if (url.includes('?page=1')) {
return Promise.resolve(ContactsFirstPageResponse);
} else {
return Promise.resolve(ContactsSecondPageResponse);
}
});
// ...
});
it('second test', async () => {
axios.get.mockImplementation(() => Promise.resolve(ContactsEmptyResponse));
// ...
});
});
First test passed, but second received response from ContactsFirstPageResponse
In addition I added auto clearing mocks on jest config:
const nextJest = require('next/jest');
const createJestConfig = nextJest({
dir: './',
});
const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig');
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest-setup.js'],
moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
resetMocks: true,
restoreMocks: true,
};
module.exports = createJestConfig(customJestConfig);
Please for help.

TypeError: moment is not a function - Angularjs Jasmine Test Case

I'm getting an issue when writing test cases for my controller in AngularJs.
Reason I have found : When i initialize the moment in my constructor I'm getting this error while running the test cases.
I'm sharing my controller code as well as test file.
class contractCancellationCtrl {
constructor(
moment) {
'ngInject';
this.moment = moment;
this.minSalesDate = moment().subtract(1, 'months').date(1);
}
define(['contract'], () => {
'use strict';
let momentMock,
ctrl,
$q,
$scope;
const dateMock = "Feb 16, 2018 10:22 AM";
fdescribe('contractCancellation', () => {
beforeEach(() => {
module('nse.contract');
momentMock = jasmine.createSpyObj('moment', ['subtract']);
momentMock.subtract.and.returnValue(dateMock);
inject((_$rootScope_, _$controller_, _$q_) => {
$scope = _$rootScope_.$new();
$q = _$q_;
ctrl = _$controller_('contractCancellationCtrl as contractCancellationCtrl', {
moment: momentMock,
});
});
contractCancellationDeferred = $q.defer();
});
it('should expect the controller to be initialized', () => {
expect(ctrl.moment).toEqual(momentMock);
});
});
});

How can i mock a component async dependency with jest

I am testing a react-native component in which imports a dependency (named import and async) which performs some logic and just returns a boolean but i think jest is not waiting for it to finish. which also logs an error.
"Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue."
currently this is the implementation i have tried..
this is the code of the test
// OfflineNotice.test.js
import React from 'react';
import { OfflineNotice } from './OfflineNotice';
jest.mock('../../service/user', () => ({
__esModule: true,
checkIfConnectivityIsValid: () => (
Promise.resolve(true)
),
}));
describe('<OfflineNotice/> test suite', () => {
const mockOnNetworkConnected = jest.fn();
test('it should render <OfflineNotice/> component', () => {
const wrapper = shallow(
<OfflineNotice
onNetworkConnected={mockOnNetworkConnected}
network={{
isConnected: true,
connectionType: 'value',
}}
/>,
);
expect(wrapper).toBeDefined();
});
});
the code of the component that i was testing
// the dependency i need to mock
import { checkIfConnectivityIsValid } from '../../service/user';
// the implementation is as follows
export class OfflineNotice extends PureComponent {
componentWillMount() {
const { network } = this.props;
const { isConnected, connectionType } = network;
this.handleConnectivityChange(isConnected, connectionType);
}
componentDidUpdate() {
const { network } = this.props;
const { isConnected, connectionType } = network;
this.handleConnectivityChange(isConnected, connectionType);
}
handleConnectivityChange = async (isConnected, connectionType) => {
const { onNetworkConnected } = this.props;
// how the service was used only returns boolean
const isValid = await checkIfConnectivityIsValid(connectionType);
let status = null;
let message = null;
if (isConnected && isValid) {
status = 'online';
message = string.NETWORK_MESSAGE.AVAILABLE;
this.fadeOut();
onNetworkConnected();
} else if (isConnected) {
status = 'invalid';
message = string.NETWORK_MESSAGE.INVALID;
this.containerOpacity.setValue(1);
} else {
status = 'offline';
message = string.NETWORK_MESSAGE.NO_INTERNET;
this.containerOpacity.setValue(1);
}
this.setState({ status, message });
};
then running the test is able to render the component. though on code coverage the code stops on the "const isValid = await checkIfConnectivityIsValid(connectionType);" part in which it says that the statement onward is not covered.