GithubHelp home page GithubHelp logo

chaijs / chai-things Goto Github PK

View Code? Open in Web Editor NEW
104.0 9.0 14.0 44 KB

Chai support for assertions on array elements

Home Page: http://chaijs.com/plugins/chai-things

License: Other

JavaScript 46.80% CoffeeScript 53.20%

chai-things's Introduction

Chai Things

Chai Things adds support to Chai for assertions on array elements.

Examples

Something

Use the something property on an array to test whether the assertion holds for one of its elements.

// Although they are equal, two different { a: 'cat' } objects are not the same
[{ a: 'cat' }, { a: 'dog' }].should.not.include({ a: 'cat' })
// Chai Things allows us to test deep equality on one of the elements
[{ a: 'cat' }, { a: 'dog' }].should.include.something.that.deep.equals({ a: 'cat' })
// If the test fails, we get a descriptive message
[{ a: 'cat' }, { a: 'dog' }].should.include.something.that.deep.equals({ a: 'cow' })
/* expected an element of [ { a: 'cat' }, { a: 'dog' } ] to deeply equal { a: 'cow' } */

You are free to choose the syntactic variant you like most:

[4, 11, 15].should.include.one.below(10)
[4, 11, 15].should.contain.some.above(10)
[4, 11, 15].should.not.contain.any.above(20)
[{ a: 'cat' }, { a: 'dog' }].should.contain.a.thing.with.property('a', 'cat')
[{ a: 'cat' }, { a: 'dog' }].should.contain.an.item.with.property('a', 'dog')

All

Use the all property on an array to test whether the assertion holds for all its elements.

// All items are below 20
[4, 11, 15].should.all.be.below(20)
// All items have a property 'a'
[{ a: 'cat' }, { a: 'dog' }].should.all.have.property('a')
// If the test fails, we get a descriptive message
[4, 11, 15].should.all.be.above(20)
/* expected all elements of [ 4, 11, 15 ] to be above 20 */
[{ a: 'cat' }, { a: 'dog' }].should.all.have.property('a', 'cat')
/* expected all elements of [ { a: 'cat' }, { a: 'dog' } ] to have a property 'a' of 'cat', but got 'dog' */

There are currently no syntactic variants for all. Let me know if you need them.

Installation and usage

$ npm install chai-things
var chai = require("chai");
chai.should();
chai.use(require('chai-things'));

Known issues

Because of how Chai works internally, it is not possible to combine Chai Things in certain ways. (See #4 and #9.)

chai-things's People

Contributors

gabrielf avatar keithamus avatar page- avatar rubenverborgh 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

chai-things's Issues

Include something that includes...

Maybe this construct isn't even supposed to work but since it's not mentioned in the README I was surprised:

describe "the array ['abc', 'def']", ->
  array = ['abc', 'def']

  it "should include something that contain 'b'", ->
    array.should.include.something.that.contain('b')

Fails with:

  1) the array ['abc', 'def'] should include something that contain 'b':
     expected 'def' to include 'b'

include.one not functioning correctly

Hey,

I want to check that exactly one element in an array has a certain property, and the others don't.
Unless I misunderstand the role of '.include.one', it seems to not function correctly. It looks like it is functioning as 'at least one', and not exactly one. For this we already have 'any'.
For example:

[5, 6, 15].should.include.one.below(10);

Is a test which passes, even though there are two elements under 10.

Omer

Chai as a peer dependency

If chai is used as a peer dependency it allows to skip the chai.use(require('chai-things')); step and just use chaiThings = require('chai-things'); with your dependencies. What do you think?

Error trying to combine "include" or "contain" with "one"

should any of these be valid?

[].should.include.one.item.with.property("isOrganizer", true);
[].should.contain.one.item.with.property("isOrganizer", true);

I receive this error:

Error: cannot use something without include or contains

all.match() is inconsistent

Hi,

I'm trying to validate an array of URLs to make sure that they all start with 'https:'.

I realized when adding one 'http:' URL that the test succeeds even though it should clearly not.

Depending on if the 'http:' URL is the first in the array or not, the test respectively fails or succeeds. It should fail in both cases.

Example:

['http://', 'https://'].should.all.match(/^https:/); // ✅ test fails as expected: AssertionError: expected [ 'http://', 'https://' ] to match /^https:/

['https://', 'http://'].should.all.match(/^https:/); // ❌ test succeeds, which is wrong

expect(['http://', 'https://']).to.all.match(/^https:/); // ✅ test fails as expected: AssertionError: expected [ 'http://', 'https://' ] to match /^https:/

expect(['https://', 'http://']).to.all.match(/^https:/); // ❌ test succeeds, which is wrong

I tried playing with 'to' and 'all': expect(...).all.match(), expect(...).all.to.match(), ... same result.

Thanks

Asserting on a property that is a specific data type

Based on chai's property assertion, I am able to do the following for an object:

expect(record).to.have.property('deleted_at').that.is.a('date);

But with chai-things, I get the following error when I try to run the following code:

expect(manyRecords).to.all.have.property('deleted_at').that.is.a('date')

## AssertionError: expected [ Array(1) ] to be a date

Although removing the data type (date) assertion does pass the test, it seems to update the target of the assertion to the provided property, instead resets to the array.

lengthOf doesn't work with nested arrays

var arr = [[], [], []];
arr[0].should.have.lengthOf(0); // test passes as expected
arr.should.all.have.property('length', 0); // test passes as expected
arr.should.all.have.lengthOf(0); // test fails saying it got a length of 3.

Type check on array of numbers fails

chai.should();

var numArray = [1,2,3,4,9882];

describe('array', function () {
    describe('numbers', function () {
        it('should all be numbers', function () {
            return numArray.should.all.be.a('number');
        });
    });
    describe('first number', function () {
        it('should be a number', function () {
            return numArray[3].should.be.a('number');
        });
    });
});

array
  elements
    1) should all be numbers
  first element
    ✓ should be a number 


1 passing (9ms)
1 failing

1) array elements should all be numbers:
   AssertionError: expected [ 1, 2, 3, 4, 9882 ] to be a number

Type check on array of numbers fails

Sorry about the issue#10, accidentally closed it!

var chai = require('chai');
require('chai-things');

chai.should();

var numArray = [1,2,3,4,9882];

describe('array', function () {
    describe('elements', function () {
        it('should all be numbers', function () {
            return numArray.should.all.be.a('number');
        });
    });
    describe('first element', function () {
        it('should be a number', function () {
            return numArray[3].should.be.a('number');
        });
    });
});

Mocha run results:

array
  elements
    1) should all be numbers
  first element
    ✓ should be a number 


1 passing (9ms)
1 failing

1) array elements should all be numbers:
   AssertionError: expected [ 1, 2, 3, 4, 9882 ] to be a number

Support for ordering

I'd like to assert that the array is sorted by some criteria. Is this something that you think can be supported?

Support for Chai 3?

Does this library work with Chai 3? After upgrading I now receive an error:

expect(res.body.data.comments).to.not.include.any.with.property('isHidden', true);

Leads to:

Fatal error: [ { _id: '8fa3d24de60f1a738a9d9dce',
    isHidden: false,
    isModerated: false } ] has no property 'isHidden'

Make Chai-Things work together with Chai-as-Promised

Hi there, I know there was an effort to make both extensions work together.
Currently I cannot use expressions such as

( promise ).should.eventually.all.have.property('property', 'value');

I get an AssertionError:

AssertionError: expected { Object (_bitField, _fulfillmentHandler0, ...) } to have a property 'length'
      at allMethod (/home/mancvso/dev/nfc/node-mongo-bare/node_modules/chai-things/lib/chai-things.js:171:37)
      at ctx.(anonymous function) [as property] (/home/mancvso/dev/nfc/node-mongo-bare/node_modules/chai/lib/chai/utils/overwriteMethod.js:48:33)
      at Context.<anonymous> (/home/mancvso/dev/nfc/node-mongo-bare/test/asana_test.js:31:73)
      at callFn (/home/mancvso/dev/nfc/node-mongo-bare/node_modules/grunt-mocha-cli/node_modules/mocha/lib/runnable.js:249:21)
      at Test.Runnable.run (/home/mancvso/dev/nfc/node-mongo-bare/node_modules/grunt-mocha-cli/node_modules/mocha/lib/runnable.js:242:7)
      at Runner.runTest (/home/mancvso/dev/nfc/node-mongo-bare/node_modules/grunt-mocha-cli/node_modules/mocha/lib/runner.js:373:10)
      at /home/mancvso/dev/nfc/node-mongo-bare/node_modules/grunt-mocha-cli/node_modules/mocha/lib/runner.js:451:12
      at next (/home/mancvso/dev/nfc/node-mongo-bare/node_modules/grunt-mocha-cli/node_modules/mocha/lib/runner.js:298:14)
      at /home/mancvso/dev/nfc/node-mongo-bare/node_modules/grunt-mocha-cli/node_modules/mocha/lib/runner.js:308:7
      at next (/home/mancvso/dev/nfc/node-mongo-bare/node_modules/grunt-mocha-cli/node_modules/mocha/lib/runner.js:246:23)
      at Object._onImmediate (/home/mancvso/dev/nfc/node-mongo-bare/node_modules/grunt-mocha-cli/node_modules/mocha/lib/runner.js:275:5)
      at processImmediate [as _immediateCallback] (timers.js:345:15)

But I can use

( promise ).should.eventually.be.an("array");

Working with bluebird promises.

If I am missing something obvious, maybe It could be a good idea to add the respective documentation.

Chai-As-Promised integration not working (possible Typescript clash?)

When parsing the values of an array returned by a promise, I get weird behavior.

Given the following versions of chai, chai-things, chai-as-promised and typescript:

+-- types@chai@3.5.2
+-- types@chai-as-promised@0.0.30
+-- types@chai-things@0.0.32
+-- chai@3.5.0
+-- chai-as-promised@6.0.0
+-- chai-things@0.2.0
+-- typescript@2.4.1

And the following import order:

import chai = require('chai');
chai.use(require('chai-things'));
chai.use(require('chai-as-promised'));
const expect = chai.expect;

And the following assertions:

expect(Promise.resolve([{ test: 'test' }])).to.eventually.all.have.property('test', 'test');
Promise.resolve([{ test: 'test' }]).should.eventually.all.have.property('test', 'test');

I get the following error:

TS2339: Property 'have' does not exist on type 'PromisedKeyFilter'.

Cannot read property 'replace' of undefined

Getting the following error when trying to use in conjunction with chai-shallow-deep-equal:

Cannot read property 'replace' of undefined

       + expected - actual


       at Context.<anonymous> (test/middleware/scheduler.spec.js:52:37)

       51 |       dispatched
       52 |     ).to.include.something.which.is.shallowDeepEqual({
       53 |       type: SCHEDULED_ACTION,

Since chai-shallow-deep-equal does not use replace anywhere, I assume the bug is with the way this library attempts to reformat the error message output?

(It works correctly when the shallowDeepEqual check succeeds - no error occurs)

include and contains?

I am attempting to assert that any element of an array of strings contains a particular substring.

The assertion ['first', 'second'].should.include.an.item.that.contains 'con' fails with expected 'second' to include 'con'.

Is this supposed to work? Without looking at the internals, I could see how using include in the sense of array elements, and contain in the sense of a substring in one assertion might be confusing.

I was expecting to expect 2 arrays of objects to be the same, but they're not

I was expecting this to return true. The only difference I can see is that the fields are in a different order. Is there something I'm missing?

expect([{
		__v: 0,
		name: 'First one',
		owner: "582a4aac593bdac822a535b6",
		_id: "582a4aad593bdac822a535b7",
		size: 0,
		cards: []
	},
	{
		__v: 0,
		name: 'SecondOne',
		owner: "582a4aac593bdac822a535b6",
		_id: "582a4aad593bdac822a535b8",
		size: 0,
		cards: []
	}
]).to.include.all.that.deep.equals([
	{
		_id: '582a4aad593bdac822a535b7',
		name: 'First one',
		owner: '582a4aac593bdac822a535b6',
		__v: 0,
		size: 0,
		cards: []
	},
	{
		_id: '582a4aad593bdac822a535b8',
		name: 'SecondOne',
		owner: '582a4aac593bdac822a535b6',
		__v: 0,
		size: 0,
		cards: []
	}
]);

Nested looping and ranges

Nested Looping

array = [ [1], [1] ];
expect(array).to.all.all.equal(1);

but then, how would we handle 3+ levels deep?:

expect(array).to.all(3).equal(1);

...but something less mathematical.

Ranged Looping

expect(array).to.each(startIndex, endIndex).equal(1);

Synonyms

each could also be a nice general synonym for all.

.all.include doesn't work as expected

When using all and include

import {expect, use} from "chai";
use(require("chai-things"));

expect(["abc", "bcd"]).to.all.include("bc");

You get the error:

AssertionError: expected 'abc' to include 'bc'

Ideally this test should pass, unless I am misunderstanding something here..

Breaks Chai all.keys

Chai's built-in all.keys assertions seem to break when I use chai-things - Chai keys

expect({a: "string", b: "string", c: "string"}).to.have.all.keys(["a", "b"])

AssertionError: expected { Object (a, b, ...) } to have a property 'length'

Boolean support is brittle

I have two use cases that will not pass with the following versions: chai@^3.5.0, chai-things@^0.2.0 and mocha@^2.4.5.

Expect all array items to be of type boolean.

Possible duplicate of #16

const bools = [false, true, false];
expect(bools).to.all.be.a('boolean');

// ERROR: expected false to be a boolean

Workaround:

expect(bools).to.all.satisfy(bool => typeof bool === 'boolean');

Expect all array items to be true (or, false).

const truths = [true, true, true];
expect(truths).to.all.be.true;

// ERROR: expected true to be true

Workaround:

expect(truths.includes(!true)).to.be.true;

If I can find the time on my hands to get a PR rolling for this, I'd be more than happy to. If for whatever reason I can't, I'd ❤️ whomever does find the time and energy to do so!

Cannot use with chai-as-promised

Basing the idea they should work off the comments here
https://gist.github.com/RubenVerborgh/4478480

and the revision on flags. I hit the following

Error: cannot use something without include or contains

when my assertion looks like this

describe('#getHardware', function() {
it('get possible related types', function(done){
var result = myConn.getHardware('faketype','fakeuid');
result.should.eventually.contain.something.with.property('type', 'battery').notify(done);
})
});

Altering to contains or includes doesn't help.

Chai is setup like this

var chai = require('chai');
var should = chai.should();
chai.use(require('chai-as-promised'));
chai.use(require('chai-things'));

Nullable array items

Trying to assert my array contains at least one null item, but I'm not sure if I'm using the library correctly. I can't seem to find a way to write it. The simple test case:

describe "nullable array items", ->
  array = ['a', 'b', null]

  it "should include something null", ->
    array.should.include.something.null

Fails with:

  1) nullable array items should include something null:
     expected null to be null

I've tried writing this in various ways, but I get similar errors:

expect(array).not.all.to.exist # AssertionError: expected null to not exist

Chai v4 support

Besides v4 general support – and since it was rewritten almost from scratch –, could issues #3 and #7 be supported now?

Thanks for this awesome package!

Change scope to the property when using should.all.have.property

Hi there
Thanks for creating this plugin it is quite useful.

One Problem I sometimes run into is the following.

In normal chai you can write something like this:

var a = {a: "a"};
a.should.have.property("a").not.equal("c"); // Test passes

var c = {a: "c"};
c.should.have.property("a").not.equal("c"); // Test fails

Is it possible to implement the same for all-validations?

Something like:

var a = {a: "a"};
var c = {a: "c"};
[a,c].should.all.have.property("a").not.equal("c"); // Test currently passes but should fail

That would be very handy.

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.