Aurelia unit testing access component's viewModel - unit-testing

I am unit testing one of my components in an Aurelia project. I'd like to access my component's viewModel in my unit test but haven't had any luck so far.
I followed the example available at https://aurelia.io/docs/testing/components#manually-handling-lifecycle but I keep getting component.viewModel is undefined.
Here is the unit test:
describe.only('some basic tests', function() {
let component, user;
before(() => {
user = new User({ id: 100, first_name: "Bob", last_name: "Schmoe", email: 'joe#schmoe.com'});
user.save();
});
beforeEach( () => {
component = StageComponent
.withResources('modules/users/user')
.inView('<user></user>')
.boundTo( user );
});
it('check for ', () => {
return component.create(bootstrap)
.then(() => {
expect(2).to.equal(2);
return component.viewModel.activate({user: user});
});
});
it('can manually handle lifecycle', () => {
return component.manuallyHandleLifecycle().create(bootstrap)
.then(() => component.bind({user: user}))
.then(() => component.attached())
.then(() => component.unbind() )
.then(() => {
expect(component.viewModel.name).toBe(null);
return Promise.resolve(true);
});
});
afterEach( () => {
component.dispose();
});
});
Here is the error I get:
1) my aurelia tests
can manually handle lifecycle:
TypeError: Cannot read property 'name' of undefined
Here is the the line that defines the viewModel on the component object but only if aurelia.root.controllers.length is set. I am not sure how to set controllers in my aurelia code or if I need to do so at all.
I guess my question is:
How do I get access to a component's viewModel in my unit tests?

Edit #2:
I'd also like to point out that your own answer is essentially the same solution as the one I first proposed in the comments. It is the equivalent of directly instantiating your view model and not verifying whether the component is actually working.
Edit:
I tried this locally with a karma+webpack+mocha setup (as webpack is the popular choice nowadays) and there were a few caveats with getting this to work well. I'm not sure what the rest of your setup is, so I cannot tell you precisely where the error was (I could probably point this out if you told me more about your setup).
In any case, here's a working setup with karma+webpack+mocha that properly verifies the binding and rendering:
https://github.com/fkleuver/aurelia-karma-webpack-testing
The test code:
import './setup';
import { Greeter } from './../src/greeter';
import { bootstrap } from 'aurelia-bootstrapper';
import { StageComponent, ComponentTester } from 'aurelia-testing';
import { PLATFORM } from 'aurelia-framework';
import { assert } from 'chai';
describe('Greeter', () => {
let el: HTMLElement;
let tester: ComponentTester;
let sut: Greeter;
beforeEach(async () => {
tester = StageComponent
.withResources(PLATFORM.moduleName('greeter'))
.inView(`<greeter name.bind="name"></greeter>`)
.manuallyHandleLifecycle();
await tester.create(bootstrap);
el = <HTMLElement>tester.element;
sut = tester.viewModel;
});
it('binds correctly', async () => {
await tester.bind({ name: 'Bob' });
assert.equal(sut.name, 'Bob');
});
it('renders correctly', async () => {
await tester.bind({ name: 'Bob' });
await tester.attached();
assert.equal(el.innerText.trim(), 'Hello, Bob!');
});
});
greeter.html
<template>
Hello, ${name}!
</template>
greeter.ts
import { bindable } from 'aurelia-framework';
export class Greeter {
#bindable()
public name: string;
}
setup.ts
import 'aurelia-polyfills';
import 'aurelia-loader-webpack';
import { initialize } from 'aurelia-pal-browser';
initialize();
karma.conf.js
const { AureliaPlugin } = require('aurelia-webpack-plugin');
const { resolve } = require('path');
module.exports = function configure(config) {
const options = {
frameworks: ['source-map-support', 'mocha'],
files: ['test/**/*.ts'],
preprocessors: { ['test/**/*.ts']: ['webpack', 'sourcemap'] },
webpack: {
mode: 'development',
entry: { setup: './test/setup.ts' },
resolve: {
extensions: ['.ts', '.js'],
modules: [
resolve(__dirname, 'src'),
resolve(__dirname, 'node_modules')
]
},
devtool: 'inline-source-map',
module: {
rules: [{
test: /\.html$/i,
loader: 'html-loader'
}, {
test: /\.ts$/i,
loader: 'ts-loader',
exclude: /node_modules/
}]
},
plugins: [new AureliaPlugin()]
},
singleRun: false,
colors: true,
logLevel: config.browsers && config.browsers[0] === 'ChromeDebugging' ? config.LOG_DEBUG : config.LOG_INFO, // for troubleshooting mode
mime: { 'text/x-typescript': ['ts'] },
webpackMiddleware: { stats: 'errors-only' },
reporters: ['mocha'],
browsers: config.browsers || ['ChromeHeadless'],
customLaunchers: {
ChromeDebugging: {
base: 'Chrome',
flags: [ '--remote-debugging-port=9333' ]
}
}
};
config.set(options);
};
tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"importHelpers": true,
"lib": ["es2018", "dom"],
"module": "esnext",
"moduleResolution": "node",
"sourceMap": true,
"target": "es2018"
},
"include": ["src"]
}
package.json
{
"scripts": {
"test": "karma start --browsers=ChromeHeadless"
},
"dependencies": {
"aurelia-bootstrapper": "^2.3.0",
"aurelia-loader-webpack": "^2.2.1"
},
"devDependencies": {
"#types/chai": "^4.1.6",
"#types/mocha": "^5.2.5",
"#types/node": "^10.12.0",
"aurelia-testing": "^1.0.0",
"aurelia-webpack-plugin": "^3.0.0",
"chai": "^4.2.0",
"html-loader": "^0.5.5",
"karma": "^3.1.1",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.3.0",
"karma-mocha-reporter": "^2.2.5",
"karma-source-map-support": "^1.3.0",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^3.0.5",
"mocha": "^5.2.0",
"path": "^0.12.7",
"ts-loader": "^5.2.2",
"typescript": "^3.1.3",
"webpack": "^4.23.1",
"webpack-dev-server": "^3.1.10"
}
}
Original answer
If you're manually doing the lifecycle, you need to pass in a ViewModel yourself that it can bind to :)
I don't remember exactly what's strictly speaking needed so I'm quite sure there's some redundancy (e.g. one of the two bindingContexts passed in shouldn't be necessary). But this is the general idea:
const view = "<div>${msg}</div>";
const bindingContext = { msg: "foo" };
StageComponent
.withResources(resources/*optional*/)
.inView(view)
.boundTo(bindingContext)
.manuallyHandleLifecycle()
.create(bootstrap)
.then(component => {
component.bind(bindingContext);
}
.then(component => {
component.attached();
}
.then(component => {
expect(component.host.textContent).toEqual("foo");
}
.then(component => {
bindingContext.msg = "bar";
}
.then(component => {
expect(component.host.textContent).toEqual("bar");
};
Needless to say, since you create the view model yourself (the variable bindingContext in this example), you can simply access the variable you declared.

In order to get it to work, I had to use Container:
import { UserCard } from '../../src/modules/users/user-card';
import { Container } from 'aurelia-dependency-injection';
describe.only('some basic tests', function() {
let component, user;
before(() => {
user = new User({ id: 100, first_name: "Bob", last_name: "Schmoe", email: 'joe#schmoe.com'});
user.save();
});
beforeEach(() => {
container = new Container();
userCard = container.get( UserCard );
component = StageComponent
.withResources('modules/users/user-card')
.inView('<user-card></user-card>')
.boundTo( user );
});
it('check for ', () => {
return component.create(bootstrap)
.then(() => {
expect(2).to.equal(2);
return userCard.activate({user: user});
});
});
});

Related

unit test with mocking custom repository of typeorm

When I tried with basic repository provided typeorm, I think test is completed.
But to do 'unit test' with custom repository of typeorm is not working.
I think mocking custom repository has problem.
What I have to do for mocking custom repostitory?
Next are test file and source file to test.
Thanks.
quests.service.spec.ts
import { Test } from '#nestjs/testing';
import { getRepositoryToken } from '#nestjs/typeorm';
import { QuestsService } from 'src/quests/quests.service';
import { QuestRepository } from 'src/quests/repositories/quest.repository';
import { Repository } from 'typeorm';
import { Complete } from 'src/quests/entities/complete.entity';
import { Player } from 'src/players/entities/player.entity';
const mockRepository = () => ({
create: jest.fn(),
save: jest.fn(),
findOne: jest.fn(),
});
const mockQuestsRepository = {
save: jest.fn(),
findOne: jest.fn(),
findAllWithCompletes: jest.fn(),
findOneWithCompletes: jest.fn(),
};
type MockRepository<T = any> = Partial<Record<keyof Repository<T>, jest.Mock>>;
type MockQuestRepository = Partial<Record<keyof QuestRepository, jest.Mock>>;
describe('QuestsService', () => {
let service: QuestsService;
let playersRepository: MockRepository<Player>;
let completeRepository: MockRepository<Complete>;
let questsRepository: MockQuestRepository;
beforeAll(async () => {
const module = await Test.createTestingModule({
providers: [
QuestsService,
{
provide: getRepositoryToken(Player),
useValue: mockRepository(),
},
{
provide: getRepositoryToken(Complete),
useValue: mockRepository(),
},
{
provide: QuestRepository,
useValue: mockQuestsRepository,
},
],
}).compile();
service = module.get<QuestsService>(QuestsService);
playersRepository = module.get(getRepositoryToken(Player));
completeRepository = module.get(getRepositoryToken(Complete));
questsRepository = module.get(QuestRepository);
});
describe('questComplete', () => {
it('should fail if quest does not exist', async () => {
questsRepository.findOne.mockResolvedValue(undefined);
const result = await service.questComplete(-1, 1);
expect(result).toEqual({
ok: false,
message: 'cant find requested Quest.',
});
});
it('should fail if player does not exist', async () => {
questsRepository.findOne.mockResolvedValue(true);
playersRepository.findOne.mockResolvedValue(undefined);
const result = await service.questComplete(1, 1);
expect(result).toEqual({
ok: false,
message: 'cant find player.',
});
});
});
});
quests.service.ts
#Injectable()
export class QuestsService {
constructor(
#InjectRepository(Complete)
private readonly completes: Repository<Complete>,
private readonly quests: QuestRepository
) {}
async questComplete(questId: number, playerId: number) {
try {
const quest = await this.quests.findOne({ id: questId });
if (!quest)
return { ok: false, message: 'cant find requested Quest.' };
const player = await Player.findOne({ where: { id: playerId } });
if (!player)
return { ok: false, message: 'cant find player.' };
const isCompleted = await this.completes.findOne({ quest, player });
if (isCompleted)
return { ok: false, message: 'quest is already completed.' };
await this.completes.save(this.completes.create({ quest, player }));
return { ok: true };
} catch (error) {
return { ok: false, message: 'quest cant be completed.' };
}
}
}

vue-test-utils does not resolve components

i've set it up in a nuxt project and when i run : npm start test it fails with the below error:
Cannot find module '#/components/Masonry' from 'components/RelatedPins/index.vue'
jest.config.js
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/$1',
'^~/(.*)$': '<rootDir>/$1',
'^vue$': 'vue/dist/vue.common.js',
},
moduleFileExtensions: ['ts', 'js', 'vue', 'json'],
transform: {
'^.+\\.ts$': 'ts-jest',
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest',
},
collectCoverage: true,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/**/*.vue',
],
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/test/mocks/fileMock.js',
'\\.(css|scss)$': '<rootDir>/test/mocks/styleMock.js',
},
}
RelatedPins.spec.js
import RelatedPins from '../components/RelatedPins'
jest.mock('axios', () => ({
get: Promise.resolve('value')
}))
describe('RelatedPins', () => {
it('mock api request', () => {
const wrapper = mount(RelatedPins, {
propsData: {
apiAddress: 'home_page/items',
httpMethod: 'post'
}
})
})
})
and this is how i import the component in my targeted testing component (RelatedPins.vue)
import Masonry from '#/components/Masonry'

How to use imported graphql files in jest unit testing?

I'm trying to run unit tests with jest but I'm getting the following error:
● Test suite failed to run
/apollo/queries/articles.gql:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){query articles($orderBy: [OrderByClause!], $stripTags: Boolean, $maxCharacters: Int) {
^^^^^^^^
SyntaxError: Unexpected identifier
I have installed
https://github.com/jagi/jest-transform-graphql
It's suppose to transform GQL files.
My package.json (jest part)
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue",
"gql"
],
"watchman": false,
"moduleNameMapper": {
"^~/(.*)$": "<rootDir>/$1",
"^~~/(.*)$": "<rootDir>/$1"
},
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest",
"\\.(gql|graphql)$": "#jagi/jest-transform-graphql"
},
"snapshotSerializers": [
"<rootDir>/node_modules/jest-serializer-vue"
],
"collectCoverage": true,
"collectCoverageFrom": [
"<rootDir>/components/**/*.vue",
"<rootDir>/pages/*.vue"
]
}
Test file
import Index from "../index";
const factory = () =>
shallowMount(Index, {
propsData: {
label: "click me!"
}
});
describe("Index", () => {
test("mounts properly", () => {
const wrapper = factory();
expect(wrapper.isVueInstance()).toBeTruthy();
});
test("renders properly", () => {
const wrapper = factory();
expect(wrapper.html()).toMatchSnapshot();
});
});
index.vue file (stripped out unimportant things)
<template>
<div></div>
</template>
<script lang="ts">
import Vue from "vue";
import ArticlesQuery from "~/apollo/queries/articles.gql";
export default Vue.extend({
name: "Homepage",
apollo: {
articles: {
query: ArticlesQuery,
variables() {
return {
orderBy: [{ field: "id", order: "DESC" }],
stripTags: true,
maxCharacters: 150
};
},
prefetch: true
}
}
});
</script>
This is my first time doing unit testing, so I have zero knowledge on this subject.
I had the same problem with Nuxt. I installed this dependence: https://www.npmjs.com/package/jest-transform-graphql, and add this: '\.(gql|graphql)$': 'jest-transform-graphql' in jest.config.js file, it works for me
transform: {
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest',
'\\.(gql|graphql)$': 'jest-transform-graphql'
},

Jest, expected mock function to have been called, but it was not called

Testing lifecycle methods when a VueJS component renders on the transition group.
I've been writing tests for lifecycle methods when the component renders on the transition group of the following VueJS component I've made little progress on getting it to work and would appreciate advice regarding this. I also tried switching between shallow mounting and mounting the component though that seemed to make no difference.
import { shallowMount } from '#vue/test-utils';
import StaggeredTransition from '../src/index';
const staggeredTransitionWrapper = componentData =>
shallowMount(StaggeredTransition, {
...componentData,
});
const staggeredTransition = staggeredTransitionWrapper();
describe('StaggeredTransition.vue', () => {
it('should render a staggered transition component', () => {
expect(staggeredTransition.element.tagName).toBe('SPAN');
expect(staggeredTransition.html()).toMatchSnapshot();
});
it('should mock calling the enter method', () => {
const enterMock = jest.fn();
StaggeredTransition.methods.enter = enterMock;
const staggeredTransitionWrapper2 = componentData =>
shallowMount(StaggeredTransition, { ...componentData });
const staggeredTransition2 = staggeredTransitionWrapper2({
slots: {
default: '<h1 :key="1">Staggered transition test</h1>',
},
});
expect(enterMock).toBeCalled();
});
});
Code for the StaggeredTransition component
<template>
<transition-group
:tag="tag"
:name="'staggered-' + type"
:css="false"
appear
#before-enter="beforeEnter"
#enter="enter"
#leave="leave"
>
<slot />
</transition-group>
</template>
<script>
const { log } = console;
export default {
name: 'StaggeredTransition',
props: {
type: {
type: String,
options: ['fade', 'slide'],
required: false,
default: 'fade',
},
tag: {
type: String,
required: false,
default: 'div',
},
delay: {
type: Number,
required: false,
default: 100,
},
},
methods: {
beforeEnter(el) {
console.log('beforeEnter');
el.classList.add(`staggered-${this.type}-item`);
},
enter(el, done) {
console.log('enter');
setTimeout(() => {
el.classList.add(`staggered-${this.type}-item--visible`);
done();
}, this.getCalculatedDelay(el));
},
leave(el, done) {
console.log('leave');
setTimeout(() => {
el.classList.remove(`staggered-${this.type}-item--visible`);
done();
}, this.getCalculatedDelay(el));
},
getCalculatedDelay(el) {
console.log('getCalculatedDelay');
if (typeof el.dataset.index === 'undefined') {
log(
'data-index attribute is not set. Please set it in order to
make the staggered transition working.',
);
}
return el.dataset.index * this.delay;
},
},
};
</script>

Angular2: Unit-test router with cached template

I'm dealing with some problems doing test on different environments:
SRC: unminified components, using both .js and .html/.css template files
DIST: minified components (only .js, no templates)
I made two different karma-conf and karma-test-shim, one for SRC and one for DIST.
In the SRC's one, since i mostly execute tests on components in fakeAsync contexts, i'm caching all my templates and .css at karma's startup, as shown in the following karma-test-shim, to avoid XHR errors.
karma-test-shim.src.js
// Turn on full stack traces in errors to help debugging
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
var karmaFiles = Object.keys(window.__karma__.files); // All files served by Karma.
window.$templateCache = {}; // deckaring Window template cache for caching .html template and .css
// Cancel Karma's synchronous start,
// we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function () { };
// Just a special configuration for Karma and coverage
System.config({
packages: {
"#angular/core/testing": { main: "../../../../../../node_modules/#angular/core/bundles/core-testing.umd.js" },
"#angular/compiler/testing": { main: "../../../../base/node_modules/#angular/compiler/bundles/compiler-testing.umd.js" },
"#angular/common/testing": { main: "../../../../base/node_modules/#angular/common/bundles/common-testing.umd.js" },
"#angular/http/testing": { main: "../../../../base/node_modules/#angular/http/bundles/http-testing.umd.js" },
"#angular/router/testing": { main: "../../../../../../node_modules/#angular/router/bundles/router-testing.umd.js" },
"#angular/platform-browser/testing": { main: "../../../../base/node_modules/#angular/platform-browser/bundles/platform-browser-testing.umd.js" },
"#angular/platform-browser-dynamic/testing": { main: "../../../../base/node_modules/#angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js" }
},
meta: {
"src/*": { format: "register" }, // Where covered files located
"packages/*": { format: "register" } // Where covered files located
}
});
Promise.all([
System.import('#angular/core/testing'),
System.import('#angular/platform-browser-dynamic/testing'),
System.import('#angular/platform-browser-dynamic') // Contains RESOURCE_CACHE_PROVIDER
]).then(function (providers) {
var testing = providers[0];
var testingBrowserDynamic = providers[1];
var browserDynamic = providers[2];
testing.TestBed.initTestEnvironment(
testingBrowserDynamic.BrowserDynamicTestingModule,
testingBrowserDynamic.platformBrowserDynamicTesting()
);
testing.TestBed.configureCompiler({
providers: [
browserDynamic.RESOURCE_CACHE_PROVIDER
]
})
// Import main module
}).then(function () {
return Promise.all(
karmaFiles
.filter(onlySpecFiles)
.map(file2moduleName)
.map(function (path) {
return System.import(path).then(function (module) {
if (module.hasOwnProperty('main')) {
module.main();
} else {
throw new Error('Module ' + path + ' does not implement main() method.');
}
});
}));
})
// Caching all component's templates files (.html/.css)
.then(function () {
return Promise.all(
karmaFiles
.filter(function (filename) {
var template = filename.endsWith('.html');
var css = filename.endsWith('.css');
return template || css;
})
.map(function (filename) {
return new Promise(function(resolve, reject) {
$.ajax({
type: 'GET',
url: filename,
dataType: 'text',
success: function (contents) {
filename = filename.replace("/base", "..");
window.$templateCache[filename] = contents;
resolve();
}
})
})
})
)
})
.then(function () {
__karma__.start();
}, function (error) {
console.error(error.stack || error);
__karma__.start();
});
// Filter spec files
function onlySpecFiles(path) {
return /\.spec\.js$/.test(path);
}
// Normalize paths to module names.
function file2moduleName(filePath) {
return filePath.replace(/\\/g, '/')
.replace(/^\/base\//, '');
}
So far so good but i started getting problems on the following spec:
loginPage.spec.js
[...]
import { LoginPageComponent } from "loginPage";
import { RESOURCE_CACHE_PROVIDER } from "#angular/platform-browser-dynamic";
#Component({
selector: "loginpage-host",
template: "<loginPage></loginPage>"
})
export class LoginPageHostComponent {
#ViewChild(LoginPageComponent)
public loginPageComponent;
}
export function main() {
describe('LoginPageComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes([]),CommonModule, HttpModule, CoreModule, ComponentsModule, GlobalizationModule],
declarations: [LoginPageHostComponent, LoginPageComponent],
providers: [
MockBackend,
BaseRequestOptions,
{
provide: AuthHttp,
useFactory: (backend: ConnectionBackend, options: BaseRequestOptions) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
},
{
provide: Http,
useFactory: (backend: ConnectionBackend, options: BaseRequestOptions) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
},
{
provide: Configuration,
useFactory: () => new Configuration()
}
]
})
// TestBed.configureCompiler({
// providers: [RESOURCE_CACHE_PROVIDER]
// });
});
it('should work',
fakeAsync(() => {
TestBed
.compileComponents()
.then(() => {
let fixture = TestBed.createComponent(LoginPageHostComponent);
let logPageHostComponentInstance = fixture.debugElement.componentInstance;
expect(logPageHostComponentInstance).toEqual(jasmine.any(LoginPageHostComponent));
expect(logPageHostComponentInstance.loginPageComponent).toEqual(jasmine.any(LoginPageComponent));
fixture.destroy();
discardPeriodicTasks();
});
}));
});
}
On SRC i get this error:
Chrome 56.0.2924 (Windows 10 0.0.0) LoginPageComponent should work
FAILED Error: Cannot make XHRs from within a fake async test.
If i manually provide the RESOURCE_CACHED_PROVIDER to the spec it works:
TestBed.configureCompiler({
providers: [RESOURCE_CACHE_PROVIDER]
});
but it fails on DIST due to the fact that there's no cached template to load for loginPage.
See: Angular2 tests and RESOURCE_CACHE_PROVIDER global
We have found a solution but not based on Angular provider.
We developed a simple karma preprocessor just for test as:
preprocessors: {
"**/*.component.js": ["generic"]
},
Then preprocessor just uses gulp-inline-ng2-template parser
genericPreprocessor: {
rules: [{
process: function (content, file, done, log) {
// Prepare content for parser
file.contents = new Buffer(content);
// Every file has a parser
var parse = require('gulp-inline-ng2-template/parser')(file, { base: "packages/", useRelativePaths: false });
// Call real parse function
parse(function (err, contents) {
// Callback with content with template and style inline
done(contents);
});
}
}]
},