angularjs unit test element $onInit binding undefined - angularjs

component
import template from './account.html';
import controller from './account.controller';
import './account.less';
const accountComponent = {
bindings: {
user: '<',
onLogout: '&'
},
template,
controller
};
export default accountComponent;
controller
class AccountController {
constructor() {}
$onInit() {
this.isVisibled = false;
this.fullname = this.user.firstName + ' ' + this.user.lastName;
}
show() {
this.isVisibled = !this.isVisibled;
}
logout() {
this.onLogout();
}
}
export default AccountController;
test
import accountModule from './index';
describe('Account', () => {
beforeEach(angular.mock.module(accountModule));
let onLogoutSpy = jasmine.createSpy('onLogout');
const bindings = {
user: {
"firstName" : "me",
"lastName" : "you"
},
onLogout: onLogoutSpy
};
let controller,
rootScope,
scope;
describe('Controller', () => {
beforeEach(inject( ($injector) => {
rootScope = $injector.get('$rootScope');
scope = rootScope.$new();
const $componentController = $injector.get('$componentController');
controller = $componentController('appAccount',{$scope:scope},bindings);
controller.$onInit();
}));
it('should be attached to the scope', () => {
expect(scope.$ctrl).toBe(controller);
});
it('isVisibled should be false', () => {
expect(controller.isVisibled).toBe(false);
});
it('fullname should be me you', () => {
expect(controller.fullname).toEqual('me you');
});
it('isVisibled should be true', () => {
controller.show();
expect(controller.isVisibled).toBe(true);
});
it('should onLogout have been called', () => {
controller.logout();
expect(onLogoutSpy).toHaveBeenCalled();
});
});
describe('Component', () => {
let element,scope;
beforeEach(inject(($rootScope, $compile) => {
dump(bindings.user);
scope = $rootScope.$new();
const markup = `
<app-account user="bindings.user"></app-account>
`;
element = angular.element(markup);
element = $compile(element)(scope);
let elementController = element.controller('app-account');
scope.$digest();
elementController.$onInit();
}));
it('xxx', () => {
//dump(element);
//const backendHeader = element.find('backend-header').eq(0);
//expect(backendHeader).toBeDefined();
});
});
});
Give me
1) xxx
Account Component
TypeError: Cannot read property 'firstName' of undefined
Can you help me to work it out, please?

I think you should write :
beforeEach(inject(($rootScope, $compile) => {
scope = $rootScope.$new();
scope.user = {
firstName "me",
lastName : "you"
}
element = $compile(`<app-account user="user"></app-account>`)(scope);
let elementController = element.controller('app-account');
scope.$digest();
}));
You're passing the user obj of the bindings object, it must be the user obj of the scope.

You do not assign bindings to the scope in your second test
scope = $rootScope.$new();
scope.bindings = bindings; // -------v
const markup = '<app-account user="bindings.user"></app-account>';

Related

Jest localStorage test [duplicate]

I keep getting "localStorage is not defined" in Jest tests which makes sense but what are my options? Hitting brick walls.
Great solution from #chiedo
However, we use ES2015 syntax and I felt it was a little cleaner to write it this way.
class LocalStorageMock {
constructor() {
this.store = {};
}
clear() {
this.store = {};
}
getItem(key) {
return this.store[key] || null;
}
setItem(key, value) {
this.store[key] = String(value);
}
removeItem(key) {
delete this.store[key];
}
}
global.localStorage = new LocalStorageMock;
Figured it out with help from this: https://groups.google.com/forum/#!topic/jestjs/9EPhuNWVYTg
Setup a file with the following contents:
var localStorageMock = (function() {
var store = {};
return {
getItem: function(key) {
return store[key];
},
setItem: function(key, value) {
store[key] = value.toString();
},
clear: function() {
store = {};
},
removeItem: function(key) {
delete store[key];
}
};
})();
Object.defineProperty(window, 'localStorage', { value: localStorageMock });
Then you add the following line to your package.json under your Jest configs
"setupTestFrameworkScriptFile":"PATH_TO_YOUR_FILE",
Answer:
Currently (Jul '22) localStorage can not be mocked or spied on by jest as you usually would, and as outlined in the create-react-app docs. This is due to changes made in jsdom. You can read about it in the jest and jsdom issue trackers.
As a workaround, you can spy on the prototype instead:
// does not work:
jest.spyOn(localStorage, "setItem");
localStorage.setItem = jest.fn();
// either of these lines will work, different syntax that does the same thing:
jest.spyOn(Storage.prototype, 'setItem');
Storage.prototype.setItem = jest.fn();
// assertions as usual:
expect(localStorage.setItem).toHaveBeenCalled();
A note on spying on the prototype:
Spying on an instance gives you the ability to observe and mock behaviour for a specific object.
Spying on the prototype, on the other hand, will observe/manipulate every instance of that class all at once. Unless you have a special usecase, this is probably not what you want.
However, in this case it makes no difference, because there only exists a single instance of localStorage.
If using create-react-app, there is a simpler and straightforward solution explained in the documentation.
Create src/setupTests.js and put this in it :
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
Tom Mertz contribution in a comment below :
You can then test that your localStorageMock's functions are used by doing something like
expect(localStorage.getItem).toBeCalledWith('token')
// or
expect(localStorage.getItem.mock.calls.length).toBe(1)
inside of your tests if you wanted to make sure it was called. Check out https://facebook.github.io/jest/docs/en/mock-functions.html
Unfortunately, the solutions that I've found here didn't work for me.
So I was looking at Jest GitHub issues and found this thread
The most upvoted solutions were these ones:
const spy = jest.spyOn(Storage.prototype, 'setItem');
// or
Storage.prototype.getItem = jest.fn(() => 'bla');
A better alternative which handles undefined values (it doesn't have toString()) and returns null if value doesn't exist. Tested this with react v15, redux and redux-auth-wrapper
class LocalStorageMock {
constructor() {
this.store = {}
}
clear() {
this.store = {}
}
getItem(key) {
return this.store[key] || null
}
setItem(key, value) {
this.store[key] = value
}
removeItem(key) {
delete this.store[key]
}
}
global.localStorage = new LocalStorageMock
or you just take a mock package like this:
https://www.npmjs.com/package/jest-localstorage-mock
it handles not only the storage functionality but also allows you test if the store was actually called.
If you are looking for a mock and not a stub, here is the solution I use:
export const localStorageMock = {
getItem: jest.fn().mockImplementation(key => localStorageItems[key]),
setItem: jest.fn().mockImplementation((key, value) => {
localStorageItems[key] = value;
}),
clear: jest.fn().mockImplementation(() => {
localStorageItems = {};
}),
removeItem: jest.fn().mockImplementation((key) => {
localStorageItems[key] = undefined;
}),
};
export let localStorageItems = {}; // eslint-disable-line import/no-mutable-exports
I export the storage items for easy initialization. I.E. I can easily set it to an object
In the newer versions of Jest + JSDom it is not possible to set this, but the localstorage is already available and you can spy on it it like so:
const setItemSpy = jest.spyOn(Object.getPrototypeOf(window.localStorage), 'setItem');
For Jest, React & TypeScript users:
I created a mockLocalStorage.ts
export const mockLocalStorage = () => {
const setItemMock = jest.fn();
const getItemMock = jest.fn();
beforeEach(() => {
Storage.prototype.setItem = setItemMock;
Storage.prototype.getItem = getItemMock;
});
afterEach(() => {
setItemMock.mockRestore();
getItemMock.mockRestore();
});
return { setItemMock, getItemMock };
};
My component:
export const Component = () => {
const foo = localStorage.getItem('foo')
localStorage.setItem('bar', 'true')
return <h1>{foo}</h1>
}
then in my tests I use it like so:
import React from 'react';
import { mockLocalStorage } from '../../test-utils';
import { Component } from './Component';
const { getItemMock, setItemMock } = mockLocalStorage();
it('fetches something from localStorage', () => {
getItemMock.mockReturnValue('bar');
render(<Component />);
expect(getItemMock).toHaveBeenCalled();
expect(getByText(/bar/i)).toBeInTheDocument()
});
it('expects something to be set in localStorage' () => {
const value = "true"
const key = "bar"
render(<Component />);
expect(setItemMock).toHaveBeenCalledWith(key, value);
}
I found this solution from github
var localStorageMock = (function() {
var store = {};
return {
getItem: function(key) {
return store[key] || null;
},
setItem: function(key, value) {
store[key] = value.toString();
},
clear: function() {
store = {};
}
};
})();
Object.defineProperty(window, 'localStorage', {
value: localStorageMock
});
You can insert this code in your setupTests and it should work fine.
I tested it in a project with typesctipt.
A bit more elegant solution using TypeScript and Jest.
interface Spies {
[key: string]: jest.SpyInstance
}
describe('→ Local storage', () => {
const spies: Spies = {}
beforeEach(() => {
['setItem', 'getItem', 'clear'].forEach((fn: string) => {
const mock = jest.fn(localStorage[fn])
spies[fn] = jest.spyOn(Storage.prototype, fn).mockImplementation(mock)
})
})
afterEach(() => {
Object.keys(spies).forEach((key: string) => spies[key].mockRestore())
})
test('→ setItem ...', async () => {
localStorage.setItem( 'foo', 'bar' )
expect(localStorage.getItem('foo')).toEqual('bar')
expect(spies.setItem).toHaveBeenCalledTimes(1)
})
})
You can use this approach, to avoid mocking.
Storage.prototype.getItem = jest.fn(() => expectedPayload);
Object.defineProperty(window, "localStorage", {
value: {
getItem: jest.fn(),
setItem: jest.fn(),
removeItem: jest.fn(),
},
});
or
jest.spyOn(Object.getPrototypeOf(localStorage), "getItem");
jest.spyOn(Object.getPrototypeOf(localStorage), "setItem");
As #ck4 suggested documentation has clear explanation for using localStorage in jest. However the mock functions were failing to execute any of the localStorage methods.
Below is the detailed example of my react component which make uses of abstract methods for writing and reading data,
//file: storage.js
const key = 'ABC';
export function readFromStore (){
return JSON.parse(localStorage.getItem(key));
}
export function saveToStore (value) {
localStorage.setItem(key, JSON.stringify(value));
}
export default { readFromStore, saveToStore };
Error:
TypeError: _setupLocalStorage2.default.setItem is not a function
Fix:
Add below mock function for jest (path: .jest/mocks/setUpStore.js )
let mockStorage = {};
module.exports = window.localStorage = {
setItem: (key, val) => Object.assign(mockStorage, {[key]: val}),
getItem: (key) => mockStorage[key],
clear: () => mockStorage = {}
};
Snippet is referenced from here
To do the same in the Typescript, do the following:
Setup a file with the following contents:
let localStorageMock = (function() {
let store = new Map()
return {
getItem(key: string):string {
return store.get(key);
},
setItem: function(key: string, value: string) {
store.set(key, value);
},
clear: function() {
store = new Map();
},
removeItem: function(key: string) {
store.delete(key)
}
};
})();
Object.defineProperty(window, 'localStorage', { value: localStorageMock });
Then you add the following line to your package.json under your Jest configs
"setupTestFrameworkScriptFile":"PATH_TO_YOUR_FILE",
Or you import this file in your test case where you want to mock the localstorage.
describe('getToken', () => {
const Auth = new AuthService();
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ik1yIEpvc2VwaCIsImlkIjoiNWQwYjk1Mzg2NTVhOTQ0ZjA0NjE5ZTA5IiwiZW1haWwiOiJ0cmV2X2pvc0Bob3RtYWlsLmNvbSIsInByb2ZpbGVVc2VybmFtZSI6Ii9tcmpvc2VwaCIsInByb2ZpbGVJbWFnZSI6Ii9Eb3Nlbi10LUdpci1sb29rLWN1dGUtbnVrZWNhdDMxNnMtMzExNzAwNDYtMTI4MC04MDAuanBnIiwiaWF0IjoxNTYyMzE4NDA0LCJleHAiOjE1OTM4NzYwMDR9.YwU15SqHMh1nO51eSa0YsOK-YLlaCx6ijceOKhZfQZc';
beforeEach(() => {
global.localStorage = jest.fn().mockImplementation(() => {
return {
getItem: jest.fn().mockReturnValue(token)
}
});
});
it('should get the token from localStorage', () => {
const result = Auth.getToken();
expect(result).toEqual(token);
});
});
Create a mock and add it to the global object
At least as of now, localStorage can be spied on easily on your jest tests, for example:
const spyRemoveItem = jest.spyOn(window.localStorage, 'removeItem')
And that's it. You can use your spy as you are used to.
This worked for me and just one code line
const setItem = jest.spyOn(Object.getPrototypeOf(localStorage), 'setItem');
2021, typescript
class LocalStorageMock {
store: { [k: string]: string };
length: number;
constructor() {
this.store = {};
this.length = 0;
}
/**
* #see https://developer.mozilla.org/en-US/docs/Web/API/Storage/key
* #returns
*/
key = (idx: number): string => {
const values = Object.values(this.store);
return values[idx];
};
clear() {
this.store = {};
}
getItem(key: string) {
return this.store[key] || null;
}
setItem(key: string, value: string) {
this.store[key] = String(value);
}
removeItem(key: string) {
delete this.store[key];
}
}
export default LocalStorageMock;
you can then use it with
global.localStorage = new LocalStorageMock();
Riffed off some other answers here to solve it for a project with Typescript. I created a LocalStorageMock like this:
export class LocalStorageMock {
private store = {}
clear() {
this.store = {}
}
getItem(key: string) {
return this.store[key] || null
}
setItem(key: string, value: string) {
this.store[key] = value
}
removeItem(key: string) {
delete this.store[key]
}
}
Then I created a LocalStorageWrapper class that I use for all access to local storage in the app instead of directly accessing the global local storage variable. Made it easy to set the mock in the wrapper for tests.
As mentioned in a comment by Niket Pathak,
starting jest#24 / jsdom#11.12.0 and above, localStorage is mocked automatically.
An update for 2022.
Jest#24+ has ability to mock local storage automatically. However, the dependency needed no longer ships with it by default.
npm i -D jest-environment-jsdom
You also need to change your Jest test mode:
// jest.config.cjs
module.exports = {
...
testEnvironment: "jsdom",
...
};
Now localStorage will already be mocked for you.
Example:
// myStore.js
const saveLocally = (key, value) => {
localStorage.setItem(key, value)
};
Test:
// myStore.spec.ts
import { saveLocally } from "./myStore.js"
it("saves key-value pair", () => {
let key = "myKey";
let value = "myValue";
expect(localStorage.getItem(key)).toBe(null);
saveLocally(key, value);
expect(localStorage.getItem(key)).toBe(value);
};
The following solution is compatible for testing with stricter TypeScript, ESLint, TSLint, and Prettier config: { "proseWrap": "always", "semi": false, "singleQuote": true, "trailingComma": "es5" }:
class LocalStorageMock {
public store: {
[key: string]: string
}
constructor() {
this.store = {}
}
public clear() {
this.store = {}
}
public getItem(key: string) {
return this.store[key] || undefined
}
public setItem(key: string, value: string) {
this.store[key] = value.toString()
}
public removeItem(key: string) {
delete this.store[key]
}
}
/* tslint:disable-next-line:no-any */
;(global as any).localStorage = new LocalStorageMock()
HT/ https://stackoverflow.com/a/51583401/101290 for how to update global.localStorage
There is no need to mock localStorage - just use the jsdom environment so that your tests run in browser-like conditions.
In your jest.config.js,
module.exports = {
// ...
testEnvironment: "jsdom"
}
none of the answers above worked for me. So after some digging this is what I got to work. Credit goes to a few sources and other answers as well.
https://www.codeblocq.com/2021/01/Jest-Mock-Local-Storage/
https://github.com/facebook/jest/issues/6798#issuecomment-440988627
https://gist.github.com/mayank23/7b994385eb030f1efb7075c4f1f6ac4c
https://github.com/facebook/jest/issues/6798#issuecomment-514266034
My full gist: https://gist.github.com/ar-to/01fa07f2c03e7c1b2cfe6b8c612d4c6b
/**
* Build Local Storage object
* #see https://www.codeblocq.com/2021/01/Jest-Mock-Local-Storage/ for source
* #see https://stackoverflow.com/a/32911774/9270352 for source
* #returns
*/
export const fakeLocalStorage = () => {
let store: { [key: string]: string } = {}
return {
getItem: function (key: string) {
return store[key] || null
},
setItem: function (key: string, value: string) {
store[key] = value.toString()
},
removeItem: function (key: string) {
delete store[key]
},
clear: function () {
store = {}
},
}
}
/**
* Mock window properties for testing
* #see https://gist.github.com/mayank23/7b994385eb030f1efb7075c4f1f6ac4c for source
* #see https://github.com/facebook/jest/issues/6798#issuecomment-514266034 for sample implementation
* #see https://developer.mozilla.org/en-US/docs/Web/API/Window#properties for window properties
* #param { string } property window property string but set to any due to some warnings
* #param { Object } value for property
*
* #example
*
* const testLS = {
* id: 5,
* name: 'My Test',
* }
* mockWindowProperty('localStorage', fakeLocalStorage())
* window.localStorage.setItem('currentPage', JSON.stringify(testLS))
*
*/
const mockWindowProperty = (property: string | any, value: any) => {
const { [property]: originalProperty } = window
delete window[property]
beforeAll(() => {
Object.defineProperty(window, property, {
configurable: true,
writable: true,
value,
})
})
afterAll(() => {
window[property] = originalProperty
})
}
export default mockWindowProperty
In my case, I needed to set the localStorage value before I check it.
So what I did is
const data = { .......}
const setLocalStorageValue = (name: string, value: any) => {
localStorage.setItem(name, JSON.stringify(value))
}
describe('Check X class', () => {
setLocalStorageValue('Xname', data)
const xClass= new XClass()
console.log(xClass.initiate()) ; // it will work
})
2022 December: Nx 14 with Angular 14 Jest.
We have an test-setup.ts file in every app and libs folder. We setting local storage mock globaly.
import 'jest-preset-angular/setup-jest';
Storage.prototype.getItem = jest.fn();
Storage.prototype.setItem = jest.fn();
Storage.prototype.removeItem = jest.fn();
Then localStorage.service.spec.ts file looking like this:
import { LocalStorageService } from './localstorage.service';
describe('LocalStorageService', () => {
let localStorageService: LocalStorageService;
beforeEach(() => {
localStorageService = new LocalStorageService();
});
it('should set "identityKey" in localStorage', async () => {
localStorageService.saveData('identityKey', '99');
expect(window.localStorage.setItem).toHaveBeenCalled();
expect(window.localStorage.setItem).toHaveBeenCalledWith('identityKey', '99');
expect(window.localStorage.setItem).toHaveBeenCalledTimes(1);
});
it('should get "identityKey" from localStorage', async () => {
localStorageService.getData('identityKey');
expect(window.localStorage.getItem).toHaveBeenCalled();
expect(window.localStorage.getItem).toHaveBeenCalledWith('identityKey');
expect(window.localStorage.getItem).toHaveBeenCalledTimes(1);
});
it('should remove "identityKey" from localStorage', async () => {
localStorageService.removeData('identityKey');
expect(window.localStorage.removeItem).toHaveBeenCalled();
expect(window.localStorage.removeItem).toHaveBeenCalledWith('identityKey');
expect(window.localStorage.removeItem).toHaveBeenCalledTimes(1);
});
});
P.S. Sorry for bad indentation, this SatckOverflow window s*cks.
First: I created a file named localStorage.ts(localStorage.js)
class LocalStorageMock {
store: Store;
length: number;
constructor() {
this.store = {};
this.length = 0;
}
key(n: number): any {
if (typeof n === 'undefined') {
throw new Error(
"Uncaught TypeError: Failed to execute 'key' on 'Storage': 1 argument required, but only 0 present."
);
}
if (n >= Object.keys(this.store).length) {
return null;
}
return Object.keys(this.store)[n];
}
getItem(key: string): Store | null {
if (!Object.keys(this.store).includes(key)) {
return null;
}
return this.store[key];
}
setItem(key: string, value: any): undefined {
if (typeof key === 'undefined' && typeof value === 'undefined') {
throw new Error(
"Uncaught TypeError: Failed to execute 'setItem' on 'Storage': 2 arguments required, but only 0 present."
);
}
if (typeof value === 'undefined') {
throw new Error(
"Uncaught TypeError: Failed to execute 'setItem' on 'Storage': 2 arguments required, but only 1 present."
);
}
if (!key) return undefined;
this.store[key] = value.toString() || '';
this.length = Object.keys(this.store).length;
return undefined;
}
removeItem(key: string): undefined {
if (typeof key === 'undefined') {
throw new Error(
"Uncaught TypeError: Failed to execute 'removeItem' on 'Storage': 1 argument required, but only 0 present."
);
}
delete this.store[key];
this.length = Object.keys(this.store).length;
return undefined;
}
clear(): undefined {
this.store = {};
this.length = 0;
return undefined;
}
}
export const getLocalStorageMock = (): any => {
return new LocalStorageMock();
};
global.localStorage = new LocalStorageMock();
Then create a test file named session.test.ts(session.test.js)
import { getLocalStorageMock } from '../localstorage';
describe('session storage', () => {
let localStorage;
beforeEach(() => {
localStorage = getLocalStorageMock();
});
describe('getItem', () => {
it('should return null if the item is undefined', () => {
expect(localStorage.getItem('item')).toBeNull();
});
it("should return '' instead of null", () => {
localStorage.setItem('item', '');
expect(localStorage.getItem('item')).toBe('');
});
it('should return navid', () => {
localStorage.setItem('item', 'navid');
expect(localStorage.getItem('item')).toBe('navid');
});
});
});
This worked for me,
delete global.localStorage;
global.localStorage = {
getItem: () =>
}

Testing and mocking a call with jest not working

I'm trying to test the following function:
// playlist.js
export function getSimplePlaylist() {
// something here
}
export function getPlaylist(type, settings) {
let options = { type };
if (type === 'simple') {
options.getData = () => {
const { videos } = settings;
return getSimplePlaylist(videos);
};
}
// There are few more cases here, but no need to post them
return options;
}
I have tried a bunch of different ways of testing that, but no luck, i.e:
//playlist.spec.js
import * as playlist from '.';
describe('getPlaylist', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it('should get correct option when static ', () => {
playlist.getSimplePlaylist = jest.fn();
const videos = playlist.getPlaylist('simple', { videos: [1, 2, 3] });
videos.getData()
expect(playlist.getSimplePlaylist).toBeCalled();
});
});
Any ideas on how I can test something like the above? Thanks!
If you use the function that way you use the JS functional programming. getPlayList will always call original getSimplePlaylist. If you want to do it you should use class:
class Playlist {
def() {
return 'def';
}
abc(cond) {
if (cond) {
return this.def();
}
}
}
export default Playlist;
and then you could test it:
import Playlist from './playlist';
describe('Name of the group', () => {
it('should ', () => {
const play = new Playlist();
play.def = jest.fn().mockReturnValue('mock');
expect(play.abc(true)).toEqual('mock');
expect(play.def).toBeCalled();
});
});
or you could use function with default implementation and then in test pass additional parameter:
// playlist.js
export function getSimplePlaylist() {
// something here
}
export function getPlaylist(type, settings, simplePlaylistFunc=getSimplePlaylist) {
let options = { type };
if (type === 'simple') {
options.getData = () => {
const { videos } = settings;
return simplePlaylistFunc(videos);
};
}
// There are few more cases here, but no need to post them
return options;
}
Probably the easiest solution here to mock function in a file would be to not export them individually but from an object and use it from that object in the particular module
// playlist.js
function getSimplePlaylist() {
// something here
}
function getPlaylist(type, settings) {
let options = { type };
if (type === 'simple') {
options.getData = () => {
const { videos } = settings;
return funcs.getSimplePlaylist(videos);
};
}
// There are few more cases here, but no need to post them
return options;
}
const funcs = {
getSimplePlaylist,
getPlaylist
}
export default funcs;
Now you can test them like
//playlist.spec.js
import playlist from '.';
describe('getPlaylist', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it('should get correct option when static ', () => {
playlist.getSimplePlaylist = jest.fn();
const videos = playlist.getPlaylist('simple', { videos: [1, 2, 3] });
videos.getData()
expect(playlist.getSimplePlaylist).toBeCalled();
});
});

Unit test for a function calling another function using jest

I'm new to Jest and having some issues to write the unit test.
My function is calling another anonymous function with some parameters.
Could you please help me fix it?
const myFunctionToTest = (code, data) => (isValid, availableCodes, defaultValue) => {
if(isValid) {
const isAvailableCode = isEmpty(availableCodes) || includes(availableCodes, code);
return isAvailableCode ? get(data, 'originalQty') : defaultValue;
}
return defaultValue;
};
Here's the mock data:
Mock data:
code: 'AB'
data: { originalQty : 2 };
isValid: true;
availableCodes: ['BCD', 'AB'];
defaultValue: 0;
What I tried!
describe('myFunctionToTest', () => {
test('it should return originally assigned quantity', () => {
const result = myFunctionToTest('AB', { originalQty: 2 } , () => {true, ['BCD', 'AB'], 0});
expect(result).toEqual(2);
});
});
Ok, I got it.
This is what I tried!
describe('myFunctionToTest', () => {
test('it should return originally assigned quantity', () => {
const result = myFunctionToTest('AB', { originalQty: 2 });
expect(result(true, ['BCD', 'AB'], 0).toEqual(2);
});
});

Trying to do a unit test for a controller with $state

I am trying to write some unit tests for my Angular 1.5 components based on this tutorial.
import notificationBannerTemplate from 'app/components/notification-banner/notification-banner.html';
const notificationBanner = {
templateUrl: notificationBannerTemplate,
controller: notificationBannerController,
bindings: {
user: '<notificationBannerUser',
onNotificationClick: '<notificationBannerOnNotificationClick',
},
};
notificationBanner.$inject = ['$state'];
function notificationBannerController($state) {
const ctrl = this;
ctrl.$onInit = function() {
ctrl.goToProfile = goToProfile;
};
function goToProfile() {
ctrl.onNotificationClick();
$state.go('app.profile.settings');
}
}
export default notificationBanner;
And my test looks like this:
import unitHelpers from 'test/unit/unit-helpers.js';
describe('notificationBanner component', () => {
let parentScope;
let element;
let state;
const $stateMock = {};
beforeEach(() => {
angular.mock.module(($provide) => {
$provide.value('$state', $stateMock);
});
});
beforeEach(angular.mock.module('CustomerComponentsModule'));
beforeEach(inject(($compile, $rootScope) => {
parentScope = $rootScope.$new();
state = jasmine.createSpyObj('$state', ['go']);
parentScope.user = {
email: 'test#test.com',
};
parentScope.closeBanner = function() {
};
element = angular.element(
`<notification-banner
notification-banner-user="user"
notification-banner-on-notification-click="closeBanner">
</notification-banner>`);
$compile(element)(parentScope);
parentScope.$digest();
}));
it('should call the goToProfile function when the button is clicked', () => {
const componentElement = unitHelpers.findByTestId(element, 'bounced-email-banner--button');
componentElement.click();
expect(state.go).toHaveBeenCalledWith('app.profile.settings');
});
});
I've tried a few different things from what I've read online, but every time I run my test I get the error TypeError: undefined is not a constructor (evaluating '$state.go('app.profile.settings')')
How can I test this?
Figured out the problem --- had to add a 'go' method to my $stateMock.
const $stateMock = {
go: jasmine.createSpy('go'),
};
Then I was able to test with expect($stateMock.go).toHaveBeenCalledWith('app.profile.settings');

How to update angular 1.2 service to 1.5 in angular 2 style

https://github.com/snapjay/ngCart/blob/master/src/ngCart.js#L30
I need to update this repo from 1.2 angular to 1.5 and in 2.0 in future
I am start to upgrade this example from addToCart component
import * as angular from 'angular';
import angularMeteor from 'angular-meteor';
import { name as ngCart } from '../../../api/ngCart/ngCart';
import './addToCart.html';
class AddToCart {
constructor($scope, $reactive) {//, ngCart
//ngCart object here should service return function?
//angular_angular.js?hash=08f63d2…:13439 TypeError: _apiNgCartNgCart.name.getItemById is not a function
'ngInject';
$reactive(this).attach($scope);
if (this.inCart()) {
this.q = ngCart.getItemById(this.id).getQuantity();
} else {
this.q = parseInt(this.quantity);
}
this.qtyOpt = [];
for (var i = 1; i <= this.quantityMax; i++) {
this.qtyOpt.push(i);
}
}
inCart() {
console.log("cart " + ngCart);
return ngCart.getItemById(this.id);
}
}
const name = 'addToCart';
// create a module
export default angular.module(name, [
angularMeteor,
ngCart
]).component(name, {
templateUrl: `imports/ui/components/${name}/${name}.html`,
controllerAs: name,
bindings: {
id: '#',
name: '#',
quantity: '#',
quantityMax: '#',
price: '#',
data: '='
},
controller: AddToCart
});
and it gives me following error
TypeError: _apiNgCartNgCart.name.getItemById is not a function
at AddToCart.inCart (addToCart.js:39)
and here ngCart service
import { name as ngCartItem } from './ngCartItem';
import { name as store } from './store';
class NgCart {
constructor($scope, $reactive, $window) {
'ngInject';
$reactive(this).attach($scope);
}
$onInit() {
// $rootScope.$on('ngCart:change', function(){ // i shouldn't user rooutscope here
// ngCart.$save();
// });
if (angular.isObject(store.get('cart'))) {
this.$restore(store.get('cart'));
} else {
this.init();
}
}
init() {
this.$cart = {
shipping: null,
taxRate: null,
tax: null,
items: []
};
};
addItem(id, name, price, quantity, data) {
var inCart = this.getItemById(id);
if (typeof inCart === 'object') {
//Update quantity of an item if it's already in the cart
inCart.setQuantity(quantity, false);
// $rootScope.$broadcast('ngCart:itemUpdated', inCart);
} else {
var newItem = new ngCartItem(id, name, price, quantity, data);
this.$cart.items.push(newItem);
// $rootScope.$broadcast('ngCart:itemAdded', newItem);
}
// $rootScope.$broadcast('ngCart:change', {});
};
getItemById(itemId) {
var items = this.getCart().items;
var build = false;
angular.forEach(items, function (item) {
if (item.getId() === itemId) {
build = item;
}
});
return build;
};
setShipping(shipping) {
this.$cart.shipping = shipping;
return this.getShipping();
};
getShipping() {
if (this.getCart().items.length == 0) return 0;
return this.getCart().shipping;
};
setTaxRate(taxRate) {
this.$cart.taxRate = +parseFloat(taxRate).toFixed(2);
return this.getTaxRate();
};
getTaxRate() {
return this.$cart.taxRate
};
getTax() {
return +parseFloat(((this.getSubTotal() / 100) * this.getCart().taxRate)).toFixed(2);
};
setCart(cart) {
this.$cart = cart;
return this.getCart();
};
getCart() {
return this.$cart;
};
getItems() {
return this.getCart().items;
};
getTotalItems() {
var count = 0;
var items = this.getItems();
angular.forEach(items, function (item) {
count += item.getQuantity();
});
return count;
};
getTotalUniqueItems() {
return this.getCart().items.length;
};
getSubTotal() {
var total = 0;
angular.forEach(this.getCart().items, function (item) {
total += item.getTotal();
});
return +parseFloat(total).toFixed(2);
};
totalCost() {
return +parseFloat(this.getSubTotal() + this.getShipping() + this.getTax()).toFixed(2);
};
removeItem(index) {
var item = this.$cart.items.splice(index, 1)[0] || {};
// $rootScope.$broadcast('ngCart:itemRemoved', item);
// $rootScope.$broadcast('ngCart:change', {});
};
removeItemById(id) {
var item;
var cart = this.getCart();
angular.forEach(cart.items, function (item, index) {
if (item.getId() === id) {
item = cart.items.splice(index, 1)[0] || {};
}
});
this.setCart(cart);
// $rootScope.$broadcast('ngCart:itemRemoved', item);
// $rootScope.$broadcast('ngCart:change', {});
};
empty() {
// $rootScope.$broadcast('ngCart:change', {});
this.$cart.items = [];
$window.localStorage.removeItem('cart');
};
isEmpty() {
return (this.$cart.items.length > 0 ? false : true);
};
toObject() {
if (this.getItems().length === 0) return false;
var items = [];
angular.forEach(this.getItems(), function (item) {
items.push(item.toObject());
});
return {
shipping: this.getShipping(),
tax: this.getTax(),
taxRate: this.getTaxRate(),
subTotal: this.getSubTotal(),
totalCost: this.totalCost(),
items: items
}
};
$restore(storedCart) {
var _self = this;
_self.init();
_self.$cart.shipping = storedCart.shipping;
_self.$cart.tax = storedCart.tax;
angular.forEach(storedCart.items, function (item) {
_self.$cart.items.push(new ngCartItem(item._id, item._name, item._price, item._quantity, item._data));
});
this.$save();
};
$save() {
return store.set('cart', JSON.stringify(this.getCart()));
}
}
const name = 'ngCart';
// create a module
export default angular.module(name, [
angularMeteor,
ngCartItem,
store
]).service(name, {
controllerAs: name,
controller: NgCart
});
How to import service in 1.5?
I am using angular-meteor and followed this tutorial
And also there can't be scope in service
// This controller throws an unknown provider error because
// a scope object cannot be injected into a service.
https://docs.angularjs.org/error/$injector/unpr?p0=$scopeProvider%20%3C-%20$scope%20%3C-%20ngCart
Found solution
Here how 1.5+ angular service should look like
import { name as store } from './store';
class NgCart {
constructor($reactive, $window) {
'ngInject';
console.log("ngcart service constructor");
}
getItemById (itemId) {
console.log("hello FROM SERVICE!");
}
}
const name = 'NgCart';
// create a module
export default angular.module(name, [
angularMeteor
]).service(name, NgCart);
and how to use it in angular component
import * as angular from 'angular';
import angularMeteor from 'angular-meteor';
import { name as NgCart } from '../../../api/ngCart/ngCart';
import './addToCart.html';
class AddToCart {
constructor($scope, $reactive, NgCart) {
'ngInject';
this.NgCart = NgCart;
}
$onInit() {
if (this.inCart()) {
this.q = this.NgCart.getItemById(this.id).getQuantity();
} else {
this.q = parseInt(this.quantity);
}
this.qtyOpt = [];
for (var i = 1; i <= this.quantityMax; i++) {
this.qtyOpt.push(i);
}
}
inCart() {
console.log("cart " + this.NgCart);
console.dir(this.NgCart);
return this.NgCart.getItemById(this.id);
}
}
const name = 'addToCart';
// create a module
export default angular.module(name, [
angularMeteor,
NgCart
]).component(name, {
templateUrl: `imports/ui/components/${name}/${name}.html`,
controllerAs: name,
bindings: {
id: '#',
name: '#',
quantity: '#',
quantityMax: '#',
price: '#',
data: '='
},
controller: AddToCart
});
Really helpfull information was in Todd Motto angular 1.x es2015 style guide
for your addToCart component, try this:
import * as angular from 'angular';
import angularMeteor from 'angular-meteor';
import { name as ngCart } from '../../../api/ngCart/ngCart';
import './addToCart.html';
class AddToCart {
constructor($scope, $reactive, ngCart) {
'ngInject';
$reactive(this).attach($scope);
this._ngCart = ngCart;
if (this.inCart()) {
this.q = this._ngCart.getItemById(this.id).getQuantity();
} else {
this.q = parseInt(this.quantity);
}
this.qtyOpt = [];
for (var i = 1; i <= this.quantityMax; i++) {
this.qtyOpt.push(i);
}
}
inCart() {
console.log("cart " + ngCart);
return this._ngCart.getItemById(this.id);
}
}
const name = 'addToCart';
// create a module
export default angular.module(name, [
angularMeteor,
ngCart
]).component(name, {
templateUrl: `imports/ui/components/${name}/${name}.html`,
controllerAs: name,
bindings: {
id: '#',
name: '#',
quantity: '#',
quantityMax: '#',
price: '#',
data: '='
},
controller: AddToCart
});
for your service, try this (services don't have scope):
import { name as ngCartItem } from './ngCartItem';
import { name as store } from './store';
class NgCart {
$onInit() {
// $rootScope.$on('ngCart:change', function(){ // i shouldn't user rooutscope here
// ngCart.$save();
// });
if (angular.isObject(store.get('cart'))) {
this.$restore(store.get('cart'));
} else {
this.init();
}
}
init() {
this.$cart = {
shipping: null,
taxRate: null,
tax: null,
items: []
};
};
addItem(id, name, price, quantity, data) {
var inCart = this.getItemById(id);
if (typeof inCart === 'object') {
//Update quantity of an item if it's already in the cart
inCart.setQuantity(quantity, false);
// $rootScope.$broadcast('ngCart:itemUpdated', inCart);
} else {
var newItem = new ngCartItem(id, name, price, quantity, data);
this.$cart.items.push(newItem);
// $rootScope.$broadcast('ngCart:itemAdded', newItem);
}
// $rootScope.$broadcast('ngCart:change', {});
};
getItemById(itemId) {
var items = this.getCart().items;
var build = false;
angular.forEach(items, function (item) {
if (item.getId() === itemId) {
build = item;
}
});
return build;
};
setShipping(shipping) {
this.$cart.shipping = shipping;
return this.getShipping();
};
getShipping() {
if (this.getCart().items.length == 0) return 0;
return this.getCart().shipping;
};
setTaxRate(taxRate) {
this.$cart.taxRate = +parseFloat(taxRate).toFixed(2);
return this.getTaxRate();
};
getTaxRate() {
return this.$cart.taxRate
};
getTax() {
return +parseFloat(((this.getSubTotal() / 100) * this.getCart().taxRate)).toFixed(2);
};
setCart(cart) {
this.$cart = cart;
return this.getCart();
};
getCart() {
return this.$cart;
};
getItems() {
return this.getCart().items;
};
getTotalItems() {
var count = 0;
var items = this.getItems();
angular.forEach(items, function (item) {
count += item.getQuantity();
});
return count;
};
getTotalUniqueItems() {
return this.getCart().items.length;
};
getSubTotal() {
var total = 0;
angular.forEach(this.getCart().items, function (item) {
total += item.getTotal();
});
return +parseFloat(total).toFixed(2);
};
totalCost() {
return +parseFloat(this.getSubTotal() + this.getShipping() + this.getTax()).toFixed(2);
};
removeItem(index) {
var item = this.$cart.items.splice(index, 1)[0] || {};
// $rootScope.$broadcast('ngCart:itemRemoved', item);
// $rootScope.$broadcast('ngCart:change', {});
};
removeItemById(id) {
var item;
var cart = this.getCart();
angular.forEach(cart.items, function (item, index) {
if (item.getId() === id) {
item = cart.items.splice(index, 1)[0] || {};
}
});
this.setCart(cart);
// $rootScope.$broadcast('ngCart:itemRemoved', item);
// $rootScope.$broadcast('ngCart:change', {});
};
empty() {
// $rootScope.$broadcast('ngCart:change', {});
this.$cart.items = [];
$window.localStorage.removeItem('cart');
};
isEmpty() {
return (this.$cart.items.length > 0 ? false : true);
};
toObject() {
if (this.getItems().length === 0) return false;
var items = [];
angular.forEach(this.getItems(), function (item) {
items.push(item.toObject());
});
return {
shipping: this.getShipping(),
tax: this.getTax(),
taxRate: this.getTaxRate(),
subTotal: this.getSubTotal(),
totalCost: this.totalCost(),
items: items
}
};
$restore(storedCart) {
var _self = this;
_self.init();
_self.$cart.shipping = storedCart.shipping;
_self.$cart.tax = storedCart.tax;
angular.forEach(storedCart.items, function (item) {
_self.$cart.items.push(new ngCartItem(item._id, item._name, item._price, item._quantity, item._data));
});
this.$save();
};
$save() {
return store.set('cart', JSON.stringify(this.getCart()));
}
}
const name = 'ngCart';
export default angular.module(name, [
angularMeteor,
ngCartItem,
store
]).service(name, NgCart);

Resources