Giter Site home page Giter Site logo

jamiemason / jasmine-matchers Goto Github PK

View Code? Open in Web Editor NEW
587.0 20.0 84.0 2.37 MB

Write Beautiful Specs with Custom Matchers for Jest and Jasmine

Home Page: https://www.npmjs.com/package/jasmine-expect

License: MIT License

JavaScript 73.40% TypeScript 26.60%
jasmine testing karma jest javascript-tests asymmetric-matchers javascript test-matchers tdd bdd

jasmine-matchers's Introduction

Jasmine-Matchers

Write Beautiful Specs with Custom Matchers

NPM version NPM downloads Build Status Maintainability

Table of Contents

Overview

What

A huge library of test matchers for a range of common use-cases, compatible with all versions of Jasmine and Jest.

Why

Custom Matchers make tests easier to read and produce relevant and useful messages when they fail.

How

By avoiding vague messages such as "expected false to be true" in favour of useful cues such as "expected 3 to be even number" and avoiding implementation noise such as expect(cycleWheels % 2 === 0).toEqual(true) in favour of simply stating that you expect(cycleWheels).toBeEvenNumber().

Sponsors
Sponsored by BrowserStack

๐ŸŒฉ Installation

npm
npm install jasmine-expect --save-dev
Bower
bower install jasmine-expect --save-dev
Manual

Downloads are available on the releases page.

๐Ÿ“ API

The Jasmine testing framework from Pivotal Labs comes with this default set of matchers:

expect().nothing()
expect().toBe(expected)
expect().toBeCloseTo(expected, precisionopt)
expect().toBeDefined()
expect().toBeFalse()
expect().toBeFalsy()
expect().toBeGreaterThan(expected)
expect().toBeGreaterThanOrEqual(expected)
expect().toBeInstanceOf(expected)
expect().toBeLessThan(expected)
expect().toBeLessThanOrEqual(expected)
expect().toBeNaN()
expect().toBeNegativeInfinity()
expect().toBeNull()
expect().toBePositiveInfinity()
expect().toBeTrue()
expect().toBeTruthy()
expect().toBeUndefined()
expect().toContain(expected)
expect().toEqual(expected)
expect().toHaveBeenCalled()
expect().toHaveBeenCalledBefore(expected)
expect().toHaveBeenCalledOnceWith()
expect().toHaveBeenCalledTimes(expected)
expect().toHaveBeenCalledWith()
expect().toHaveClass(expected)
expect().toHaveSize(expected)
expect().toMatch(expected)
expect().toThrow(expectedopt)
expect().toThrowError(expectedopt, messageopt)
expect().toThrowMatching(predicate)
expect().withContext(message)

and this default set of asymmetric matchers;

jasmine.any(Constructor);
jasmine.anything(mixed);
jasmine.arrayContaining(mixed);
jasmine.objectContaining(mixed);
jasmine.stringMatching(pattern);

Matchers

Jasmine-Matchers adds the following matchers:

expect(array).toBeArray();
expect(array).toBeArrayOfBooleans();
expect(array).toBeArrayOfNumbers();
expect(array).toBeArrayOfObjects();
expect(array).toBeArrayOfSize(number);
expect(array).toBeArrayOfStrings();
expect(array).toBeEmptyArray();
expect(array).toBeNonEmptyArray();
expect(boolean).toBeBoolean();
expect(date).toBeAfter(otherDate);
expect(date).toBeBefore(otherDate);
expect(date).toBeDate();
expect(date).toBeValidDate();
expect(fn).toBeFunction();
expect(fn).toThrowAnyError();
expect(fn).toThrowErrorOfType(constructorName);
expect(mixed).toBeCalculable();
expect(number).toBeEvenNumber();
expect(number).toBeGreaterThanOrEqualTo(otherNumber);
expect(number).toBeLessThanOrEqualTo(otherNumber);
expect(number).toBeNear(otherNumber, epsilon);
expect(number).toBeNumber();
expect(number).toBeOddNumber();
expect(number).toBeWholeNumber();
expect(number).toBeWithinRange(floor, ceiling);
expect(object).toBeEmptyObject();
expect(object).toBeNonEmptyObject();
expect(object).toBeObject();
expect(object).toHaveArray(memberName);
expect(object).toHaveArrayOfBooleans(memberName);
expect(object).toHaveArrayOfNumbers(memberName);
expect(object).toHaveArrayOfObjects(memberName);
expect(object).toHaveArrayOfSize(memberName, size);
expect(object).toHaveArrayOfStrings(memberName);
expect(object).toHaveBoolean(memberName);
expect(object).toHaveCalculable(memberName);
expect(object).toHaveDate(memberName);
expect(object).toHaveDateAfter(memberName, date);
expect(object).toHaveDateBefore(memberName, date);
expect(object).toHaveEmptyArray(memberName);
expect(object).toHaveEmptyObject(memberName);
expect(object).toHaveEmptyString(memberName);
expect(object).toHaveEvenNumber(memberName);
expect(object).toHaveFalse(memberName);
expect(object).toHaveHtmlString(memberName);
expect(object).toHaveIso8601(memberName);
expect(object).toHaveJsonString(memberName);
expect(object).toHaveMember(memberName);
expect(object).toHaveMethod(memberName);
expect(object).toHaveNonEmptyArray(memberName);
expect(object).toHaveNonEmptyObject(memberName);
expect(object).toHaveNonEmptyString(memberName);
expect(object).toHaveNumber(memberName);
expect(object).toHaveNumberWithinRange(memberName, floor, ceiling);
expect(object).toHaveObject(memberName);
expect(object).toHaveOddNumber(memberName);
expect(object).toHaveString(memberName);
expect(object).toHaveStringLongerThan(memberName, string);
expect(object).toHaveStringSameLengthAs(memberName, string);
expect(object).toHaveStringShorterThan(memberName, string);
expect(object).toHaveTrue(memberName);
expect(object).toHaveUndefined(memberName);
expect(object).toHaveWhitespaceString(memberName);
expect(object).toHaveWholeNumber(memberName);
expect(regexp).toBeRegExp();
expect(string).toBeEmptyString();
expect(string).toBeHtmlString();
expect(string).toBeIso8601();
expect(string).toBeJsonString();
expect(string).toBeLongerThan(otherString);
expect(string).toBeNonEmptyString();
expect(string).toBeSameLengthAs(otherString);
expect(string).toBeShorterThan(otherString);
expect(string).toBeString();
expect(string).toBeWhitespace();
expect(string).toEndWith(substring);
expect(string).toStartWith(substring);

Asymmetric Matchers

any.after(date);
any.arrayOfBooleans();
any.arrayOfNumbers();
any.arrayOfObjects();
any.arrayOfSize(number);
any.arrayOfStrings();
any.before(date);
any.calculable();
any.emptyArray();
any.emptyObject();
any.endingWith(string);
any.evenNumber();
any.greaterThanOrEqualTo(number);
any.iso8601();
any.jsonString();
any.lessThanOrEqualTo(number);
any.longerThan(string);
any.nonEmptyArray();
any.nonEmptyObject();
any.nonEmptyString();
any.oddNumber();
any.regExp();
any.sameLengthAs(string);
any.shorterThan(string);
any.startingWith(string);
any.whitespace();
any.wholeNumber();
any.withinRange(floor, ceiling);

๐Ÿ•น Usage

Browser

Embed jasmine-matchers.js after Jasmine but before your tests.

Jest

Include the following in your package.json:

"unmockedModulePathPatterns": ["jasmine-expect"]

And the following at the top of your test suite:

import JasmineExpect from "jasmine-expect";

Karma

Integration is easy with the karma-jasmine-matchers plugin.

Node.js

Use the Jasmine CLI and include the path to where Jasmine Matchers is installed in the helpers array of your spec/support/jasmine.json.

{
  "spec_dir": "spec",
  "spec_files": ["../src/**/*.spec.js"],
  "helpers": ["../node_modules/jasmine-expect/index.js"],
  "stopSpecOnExpectationFailure": false,
  "random": false
}

TypeScript and Angular CLI Projects

If you are using TypeScript, you might want to npm install @types/jasmine-expect --save-dev in order to prevent your IDE from complaining about the new Matchers.

Also, if you run into TypeScript compilation errors when running your tests, add "jasmine-expect" to the "types" array in your tests' tsconfig file.

As an example, for an Angular CLI based project, this would be your tsconfig.spec.json file:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "baseUrl": "./",
    "module": "commonjs",
    "target": "es5",
    "types": ["jasmine", "node", "jasmine-expect"]
  },
  "files": ["test.ts"],
  "include": ["**/*.spec.ts", "**/*.d.ts"]
}

Sublime Text

Jasmine-Matchers-Snippets or Jasmine-Matchers-ES6-Snippets can be installed with Package Control to ease development with Jasmine Matchers in Sublime Text.

Tern

There is a Plugin for Tern to auto-complete matchers in your Text Editor.

๐ŸŒ Browser Support

Jasmine-Matchers is tested on Travis CI and BrowserStack against the following environments.

Browser Version Range
Android 9 - 11
Chrome 80 - 85
Edge 80 - 85
Firefox 76 - 80
iOS 10 - 14
Safari 10 - 13

๐Ÿ™‹๐Ÿฝโ€โ™‚๏ธ Getting Help

Get help with issues by creating a Bug Report or discuss ideas by opening a Feature Request.

๐Ÿ‘€ Other Projects

If you find my Open Source projects useful, please share them โค๏ธ

๐Ÿค“ Author

I'm Jamie Mason from Leeds in England, I began Web Design and Development in 1999 and have been Contracting and offering Consultancy as Fold Left Ltd since 2012. Who I've worked with includes Sky Sports, Sky Bet, Sky Poker, The Premier League, William Hill, Shell, Betfair, and Football Clubs including Leeds United, Spurs, West Ham, Arsenal, and more.

Follow JamieMason on GitHubย ย ย ย ย ย Follow fold_left on Twitter

jasmine-matchers's People

Contributors

bennycode avatar boldfacedesign avatar ik9999 avatar jacobwardio avatar jamiemason avatar jmandreslopez avatar marcin-wosinek avatar matheo avatar sjwall avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jasmine-matchers's Issues

StealJS

I am having problems getting this to work with StealJS.

Not obvious how to use Jasmine-Matchers with Karma

I do the "npm install" per your README, and then I have to add a line to the "files" array in my karma.conf.js:

        files: [
            'node_modules/jasmine-expect/dist/jasmine-matchers.js',
            'src/main/webapp/js/angular/angular.js',
            'src/main/webapp/js/angular/angular-*.js',
            ... etc ...

If I don't add that line, I can't use your matchers in my tests. Am I doing this correctly, or is there some other way I ought to be doing it? Thanks!

expect(object).toHaveUndefined('memberName');

Use case is in ui-router state params for example, where you might want to assert that a state of a given name exists as part of the state's configuration, but that no default value has been assigned to it.

Current spec

it('should not set a default value for the dateFrom param', function() {
    expect($state.params).toHaveMember('dateFrom');
    expect($state.params.dateFrom).toBeUndefined();
});

Current output

Expected member "dateFrom" of Object({  }) to be member.
Expected undefined not to be undefined

Preferred spec

it('should not set a default value for the dateFrom param', function() {
    expect($state.params).toHaveUndefined('dateFrom');
});

Preferred output

Expected Object({  }) to have undefined member "dateFrom".

Move matchers to separate file?

Jest is based on Jasmine, i want to extend Jest with your matchers, but index.js fires lib/factory. Can you please move matchers to separate matchers.js file, so i can access matchers collection without firing factory?

Protractor configuration?

Sorry for the n00b question, I'm fairly new to Protractor and Jasmine. I'm using Protractor to do e2e testing and would like to use these matchers. However, I'm not able to get protractor to recognize these matchers. I've followed directions for NodeJS in the README, used npm to install the module, and can see the module in my project's node_modules directoyr. I've applied the path to "helpers" in the jasmine.json file in protractor's spec/support subdirectory, but I still get

Failed: expect(...).toBeArray is not a function

Any suggestions would be greatly appreciated.

Add example protractor project

Similar to the Jest and Node.js/Jasmine CLI examples, this issue is to create a minimal working example of a Protractor project which uses jasmine-expect.

npm test should run the tests.

.
โ”œโ”€โ”€ examples
โ”‚ย ย  โ”œโ”€โ”€ protractor
โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ package.json
โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ ...whatever else protractor needs

There is also some useful info in #60.

expect not stop execution when fail.

In testNg, There is assert and verify methods are available.
Assert(hard assert) -: assert stop execution when assertion fail.
Verify(soft assert) -: verify continue execution even though fail verification method.

so we can use assert and verify according our requirement so is there any functionality available in jasmine?

expect(array).toBeArrayOfObjectsContaining(descriptor);

Example
expect(this.colleagues).toBeArrayOfObjectsContaining({
  name: jasmine.any(String),
  age: jasmine.any(Number)
});
Implementation

Internally we would assert this.colleagues is an Array, then assert that every member passes;

expect(member).toEqual(jasmine.objectContaining({
  age: jasmine.any(Number),
  name: jasmine.any(String)
}));

expect(foo).toHaveMethod('bar'); should output what method name was missing.

I'd like to be able to read what method name is missing from an object when an assertion fails. Thoughts?

var foo = {
  notbar: function () { return }
};

expect(foo).toHaveMethod('bar');

// Current: Expected Object({ notbar: Function }) to have method.
// Desired: Expected Object({ notbar: Function }) to have method 'bar'.

expect(object).toHave*

Re-use matchers available for regular values to inspect objects.

expect(obj).toHaveMethod('get');
expect(obj).toHaveMember('falsy');
expect(obj).toHaveString('status');
expect(obj).toHaveNonEmptyString('name');

The aim is to improve the readability of error messages, changing today's approach;

expect(obj.get).toBeFunction();

    PhantomJS 1.9.7 (Mac OS X)
      obj
         when instantiated
            should expose the expected API FAILED

       Expected null to be function.

To the following;

expect(obj).toHaveMethod('get');

    PhantomJS 1.9.7 (Mac OS X)
      obj
         when instantiated
            should expose the expected API FAILED

       Expected { get : null } to have method 'get'.

expect('123').toBeNumericString();

expect('123').toBeNumericString();
expect('1,234,567.00').toBeNumericString();
expect('   123  ').not.toBeNumericString();
expect('1..0').not.toBeNumericString();

Jasmine 2.0 toThrowError

Hi,

It seems Jasmine 2.0 has a toThrowError which (no offence) seems to be better (it can check both exception type and message). A few questions:

  • It seems that jasmine-expects's toThrowError overrides jasmine's; is that intentional?
  • Is there anyway I can invoke jasmine's version of the function, am I missing something obvious?

Thanks

require('jasmine-expect') API can only register watchers once

We're trying to use jasmine-expect to test a node.js application using gulp-jasmine. The current require('jasmine-expect') API isn't sufficient for that use case, since it only registers the matchers once. When the watcher runs the tests a second time, the require() result is already cached and the matchers aren't registered.

A function that registers the matchers when called would solve this issue. Not sure how to integrate it without breaking backwards compatibility or registering the matchers multiple times, though.

instanceof checks may not be sufficient in node

This is sort of an edge case, so I'd understand if you didn't want to bother with it. I just added this package to our jasmine suite, and .toBeFunction() is reporting "Expected Function to be function." The reason is that we are using sandboxed-module, which loads the subject under test using the vm module (in a separate context). instanceof doesn't seem to work when comparing objects from different contexts. E.g. (in our case):

// vm context - i.e. the subject-under-test
exports.a = function() {}
// test
expect(obj.a).toBeFunction() // fails because obj.a instanceof Function is false

For what's it worth, I don't blame you for this. The vm context instanceof problem is super annoying, and I've run into it before too. You might be able to do other checks in addition to instanceof to cover such cases. Something like return this.actual isntanceof Function || typeof this.actual === 'function' || this.actual.apply.

.toImplement does not properly check type

The example for .toImplement() uses a hash where the key must exist, and implies that the value is the type the actual value should be. This method does not seem to test for individual types off the actual object, and fails when we build a mock object that is exactly what the test expects, ie:

This will pass:

expect({
  foo: 'bar',
  baz: 123,
  foobarbaz: [1, 2, 3]
}).toImplement({
  foo: String,
  baz: Number,
  foobarbaz: Array
})

but so will this:

expect({
  foo: 'bar',
  baz: '123',
  foobarbaz: [1, 2, 3]
}).toImplement({
  foo: String,
  baz: Number,
  foobarbaz: Array
})

Even though baz is a string but is expected to be a number.

If this is just checking for the existance of all attributes, why not have toImplement accept an array of the hash keys?

Reason field should be present if expect fails

Hi All,

Jasmine expect matchers covers vast asserting statement but one feature that will really make it great is adding a Reason field if any of the test has Failed.
I search a lot for this and many people also thinks the same way.
Please add this feature.

Thanks
Mohit Gupta

Deprecate .toImplement

Hi,

Not sure if these are intended features of .toImplement or not but I find the following behaviours (introduced in #42 / 866e832 ) to be counterintuitive:

Testing if an object implements a field that is null/undefined

var actual = { fieldA: 'a value', fieldB: null };
var expected = { fieldA: String, fieldB: null };
expect(actual).toImplement(expected);

Produces:

Chrome 48.0.2564 (Windows 10 0.0.0) The bawResource service test FAILED
        TypeError: Cannot read property 'constructor' of null
            at featuresAll ([OMITTED]/vendor/jasmine-expect/dist/jasmine-matchers.js:1723:62)
            at toImplement ([OMITTED]/vendor/jasmine-expect/dist/jasmine-matchers.js:1718:17)
            at compare ([OMITTED]/vendor/jasmine-expect/dist/jasmine-matchers.js:374:38)
            at Object.<anonymous> ([OMITTED]/es6/src/components/services/bawResource.spec.js:55:24 <- ../../../../src/components/services/bawResource.spec.js:55:23)

Expected result

The test case to pass . Even if not intended to pass, the exception breaks the test reporter. The matcher should return false and not throw.

It seems valid to me that an object be required to have a field even if its value is null - as null is valid value. The argument for undefined is a little less convincing but I'd personally still expect it to work.

Testing if a function object implements an interface:

        var actual = function noop(){};
        actual.extraField = "some useful property";
        actual.extraFunction = function noop2() {};

        var expected = { extraField: String, extraFunction: Function };
        expect(actual).toImplement(expected);

Produces:

Chrome 48.0.2564 (Windows 10 0.0.0) The bawResource service test FAILED
        Expected Function to implement Object({ extraField: Function, extraFunction: Function }).
            at Object.<anonymous> ([OMITTED]/es6/src/components/services/bawResource.spec.js:58:24 <- ../../../../src/components/services/bawResource.spec.js:58:23)

Expected

The test case to pass. A function is a valid object just like any other.

Are these properties intended behaviour?

expect(object).toExtend(Constructor);

A developer would be forgiven for expecting expect([]).toBeObject() to return false since Arrays are different to Objects in significant ways.

The case however with Jasmine-Matchers, _.isObject([]) (lodash/underscore), angular.isObject([]), and others is a return value of true โ€” because Array extends Object.

Implement expect(object).toExtend(Constructor); and consider changing expect([]).toBeObject() to return false as a breaking change in version 2 โ€” with a recommendation to instead use expect([]).toExtend(Object) for those cases when that behaviour is desirable.

Update readme in latest tagged release.

This library is very useful! Thanks for all of the hard work that you put into this. I found it unfortunate that the list of available functions didn't match up with what is actually in 1.22.2. Also, is 1.20.0 still the latest stable version as stated in the readme on master?

Adding this library to an Angular 2 project using Jasmine

Hi all!

I think this is not an issue but can be an improvement in the doc.

I'm developing an Angular 2 RC5 app with Jasmine and I'm trying to load this library.

What I've done is:

In a unit-tests.html file I've included the following:


<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <title>Ng App Unit Tests</title>
    <link rel="stylesheet" href="node_modules/jasmine-core/lib/jasmine-core/jasmine.css">
    <!-- #1. Polyfills -->
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <!-- #2. Zone.js dependencies -->
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/zone.js/dist/async-test.js"></script>
    <script src="node_modules/zone.js/dist/fake-async-test.js"></script>
    <!-- #3. Add specs dependencies -->
    <script src="app/treeNode.spec.ts"></script>
    <script src="app/template.spec.ts"></script>
    <script src="app/services/tree.side.service.spec.ts"></script>
    <script src="app/services/tree.service.spec.ts"></script>
    <!-- #4. Add Jasmine dependencies -->
    <script src="node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script>
    <script src="node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
    <script src="node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>
    <script src="node_modules/jasmine-expect/dist/jasmine-matchers.js"></script>
[...]

And then, I've created a Spec file, like this:

describe('Service: TreeService', () => {

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                {provide: TreeService, useClass: TreeService},
                [...]
            ]
        })
    });

    it('get nodes',
        inject(
            [TreeService], fakeAsync((service: TreeService, backend: MockBackend) => {
                let res: TreeNode[];
                service.provider = '/test/api/treeNodes';
                service.getNodes();
                service.nodes.subscribe((response) => {
                    res = response as TreeNode[];
                });
                tick(500);
                expect(res).toBeArray();
                expect(res).toBeNonEmptyArray();
                expect(res.length).toBeGreaterThan(0);
            })));
});

But when I run the app, with npm test this error occurs:

app/services/tree.service.spec.ts(39,29): error TS2339: Property 'toBeArray' does not exist on type 'Matchers'.
app/services/tree.service.spec.ts(40,29): error TS2339: Property 'toBeNonEmptyArray' does not exist on type 'Matchers'.

So I don't know how to import this matcher inside the Spec file.

Any help is appreciate ;)

Thanks!

[EDIT]
As I mentioned, I believe this is not an issue, because I finally solve this problem. I've missed some important thing to do, considering I'm using TypeScript:

typings install dt~jasmine-expect --save-dev -DG

With this, a globalDevDependencies is added in file typings.json and this library is available to use.

I think that the documentation is great and very useful, but maybe it could be improve with a section explain how to use with TypeScript.

Thanks a lot!

Documentation should show what matchers are in beta

Currently, running the recommended npm or bower installation methods installs v1.22.3. This does not seem to have a lot of the methods as shown in the documentation.

If possible please specify what features are there in beta until a full release of 2.0 or explicitly add the version within the installation instructions.

2.0.0-beta3: Cannot find module './src/jasmine-matchers'

Hi folks. Just noticed this error after installing beta3. Was not present in beta2. Hope it helps! Let me know if I can provide additional assistance. :-)

Users/eml/Projects/qlearning/qlearning_webapp/node_modules/jasmine-expect/index.js: Cannot find module './src/jasmine-matchers' from '/Users/eml/Projects/project/node_modules/jasmine-expect/index.js'
  at Loader._getNormalizedModuleID (/Users/eml/Projects/project/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:349:15)
  at Loader._shouldMock (/Users/eml/Projects/project/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:558:23)
  at Loader.requireModuleOrMock (/Users/eml/Projects/project/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:920:12)
  at Object.<anonymous> (/Users/eml/Projects/project/node_modules/jasmine-expect/index.js:3:18)
  at Object.runContentWithLocalBindings (/Users/eml/Projects/project/node_modules/jest-cli/src/lib/utils.js:527:17)
  at Loader._execModule (/Users/eml/Projects/project/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:239:9)
  at Loader.requireModule (/Users/eml/Projects/project/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:902:12)
  at Loader._generateMock (/Users/eml/Projects/project/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:270:30)
  at Loader.requireMock (/Users/eml/Projects/project/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:798:43)
  at Loader.requireModuleOrMock (/Users/eml/Projects/project/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:921:17)
  at Object.<anonymous> (/Users/eml/Projects/project/__tests__/client/utils/testQlearningApiSpec.js:2:117)
  at Object.runContentWithLocalBindings (/Users/eml/Projects/project/node_modules/jest-cli/src/lib/utils.js:527:17)
  at Loader._execModule (/Users/eml/Projects/project/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:239:9)
  at Loader.requireModule (/Users/eml/Projects/project/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:902:12)
  at jasmineTestRunner (/Users/eml/Projects/project/node_modules/jest-cli/src/jasmineTestRunner/jasmineTestRunner.js:284:16)
  at /Users/eml/Projects/project/node_modules/jest-cli/src/TestRunner.js:379:12

expect(object).toBeObjectContaining(descriptor)

Example
expect(value).toBeObjectContaining({
  age: jasmine.any(Number),
  name: jasmine.any(String)
});
Implementation

This would be sugar for

expect(value).toEqual(jasmine.objectContaining({
  age: jasmine.any(Number),
  name: jasmine.any(String)
}));

expect(something).toBeNaN();

Hi !

Could be a great feature. Use global isNaN plus polyfills if Number.isNaN is not available (harmony feature)

Generate Jasmine-Matchers-Snippets

There are two Sublime Text Packages which are currently manually updated;

Finding some way to generate these projects using the source code from this one would be a time-saver and also be less error-prone. Something like Esprima could be used, or something more crude like a node.js script which imports jasmine-expect then loops over the API to get hold of the method names and argument names.

Add .toBeValidDate()

I would expect that this test would fail for invalid dates:
expect(new Date("invalid")).toBeDate()

Or that there would be a test like:
expect(new Date("invalid")).toBeValidDate()

Workaround could be:
expect(new Date("invalid")).toBeAfter(new Date(0));

Availability through bower

There are plan to make this library available via bower?

I understand you can install it via npm, but this is not a reliable solution for me ( usin nvm node_modules are in my home folder ).

Suggestion: change repository structure so master is always the latest released version

I would suggest something about how the repository is structured at this point and why I think it is better to do it in that way.

At this point, whenever people go the repo to check documentation, they can see the documentation of master, which is the next version that is going to be released at some point. But the problem is there will be breaking changes in the next version because there are new and old matchers remove.

What everyone needs to do now is to go to the repo, and select the 1.22.2 tag to see actually the documentation of the latest available version.

This issue could have been solved following more a git-flow approach, where master always contains the latest released version, and you develop the new one in a different branch (usually "develop"). And master is only upgraded once you release a new one.

With this new flow, everyone who land in the project main page, you will always see the right documentation.

Thanks

Expect an array to be sorted

Recently, I've encountered the need to expect an array to be sorted alphabetically. Would it be a good idea to have a custom jasmine matcher for this particular situation?

expect(arr).toBeSorted(); 

Thanks!

expect(floatNumber).toBeNear(number, epsilon)

Compare a given value numerically to be in the range of number-epsilon and number+epsilon. Thus epsilon specifies the maximum tolerance the compared value is allowed to vary.

Example

expect(4.23223432434).toBeNear(4, 0.25); // success
expect(4.23223432434).toBeNear(4, 0.2); // failure

Implementation

Could internally use the "toBeWithinRange" matcher, but the above is much nicer to write if you're not targeting a specific range, but just a value and allow some wobbling.

Improve toBeHtmlString()

    Expected '<a data-ng-href="//www.nowtv.com" data-ng-click="launchApp($event)" target="_blank" class="ng-binding" href="//www.nowtv.com">
      Watch with NOW TV
    </a>' to be html string.

Jest installation not working

Followed directions for the Jest installation, but I get:

TypeError: this.addMatchers is not a function
      at Object.<anonymous> (node_modules/jasmine-matchers/src/toThrow.js:2:8)

Asymmetric matchers

Example usage

expect(spy).toHaveBeenCalledWith(any.arrayOfObjectsContaining({
  name: jasmine.any(String),
  age: jasmine.any(Number)
}));
expect(adult).toEqual({
  name: any.nonEmptyString(),
  dateOfBirth: any.dateBefore(new Date(/* 18 years ago */)),
  favouriteNumbers: any.arrayOfNumbers()
});

Jasmine Default Matchers
any.defined();
any.falsy();
any.greaterThan(number);
any.lessThan(number);
any.truthy();
any.containing(member);
any.containing(substring);
any.thatMatch(pattern);
Arrays
any.arrayOfBooleans();
any.arrayOfNumbers();
any.arrayOfObjects();
any.arrayOfObjectsContaining(descriptor);
any.arrayOfSize(5);
any.arrayOfStrings();
any.emptyArray();
any.nonEmptyArray();
Dates
any.dateAfter(new Date());
any.dateBefore(new Date());
Numbers
any.calculable();
any.evenNumber();
any.numberWithinRange(number, number);
any.oddNumber();
any.wholeNumber();
Objects
any.emptyObject();
any.nonEmptyObject();
any.objectContaining(descriptor);
Strings
any.emptyString();
any.jsonString();
any.nonEmptyString();
any.stringEndingWith(string);
any.stringLongerThan(string);
any.stringSameLengthAs(string);
any.stringShorterThan(string);
any.stringStartingWith(string);
any.whitespace();
References

expect(collection).toContainValues(array);

I'm looking for something like this:

day_names = { mon: 'Monday', wed: 'Wednesday', tue: 'Tuesday' }
possible_day_names = ['Monday', 'Tuesday', 'Wednesday']
expect(_.values(day_names)).toBeInAnyOrder(possible_day_names)

I've found this pattern useful, when working over collections or objects that I know might come in a different order than what I might specify in the test. If the order is unimportant, the fact that I just have these items and only these items might be a good utility method to have on this library.

You'd implement it with the Lodash _.xor method, and determine if it's an empty array. If there are differences, maybe these should also be returned to expect and the user notified of the differences.

This is different than 'to have in any order', because _.xor isn't thinking about what's optional.

This plugin works great with grunt-jasmine-bundle, btw!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.