Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.toThrowError() #1301

Merged
merged 1 commit into from
Aug 17, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ exports[`test console printing 1`] = `
This is a error message.
PASS __tests__/console2-test.js
● Console
error __tests__/console2-test.js:11
error __tests__/console2-test.js:18
This is an error from another test file."
`;

Expand All @@ -28,7 +28,7 @@ exports[`test console printing with --verbose 1`] = `
error __tests__/console-test.js:17
This is a error message.

error __tests__/console2-test.js:11
error __tests__/console2-test.js:18
This is an error from another test file.

"
Expand Down
2 changes: 1 addition & 1 deletion integration_tests/__tests__/console-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ test('console printing', () => {
});

test('console printing with --verbose', () => {
const result = runJest('console', ['--verbose']);
const result = runJest('console', ['--verbose', '--no-cache']);
const stdout = result.stdout.toString();

expect(result.status).toBe(0);
Expand Down
11 changes: 9 additions & 2 deletions integration_tests/console/__tests__/console2-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@
*/
'use strict';

jest.useRealTimers();

test('works just fine', () => {
console.error('This is an error from another test file.');
return new Promise(resolve => {
// Make the second test finish last to get consistent console
// output
setTimeout(resolve, 3000);
}).then(() => {
console.error('This is an error from another test file.');
});
});

3 changes: 3 additions & 0 deletions packages/jest-matcher-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@
"main": "build/index.js",
"scripts": {
"test": "../../packages/jest-cli/bin/jest.js"
},
"dependencies": {
"chalk": "^1.1.3"
}
}
2 changes: 2 additions & 0 deletions packages/jest-matcher-utils/src/__tests__/index-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,6 @@ describe('.getType()', () => {
test('function', () => expect(getType(() => {})).toBe('function'));
test('boolean', () => expect(getType(true)).toBe('boolean'));
test('symbol', () => expect(getType(Symbol.for('a'))).toBe('symbol'));
test('regexp', () => expect(getType(/abc/)).toBe('regexp'));

});
26 changes: 22 additions & 4 deletions packages/jest-matcher-utils/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,19 @@

'use strict';

import type {ValueType} from 'types/Values';
export type ValueType =
| 'array'
| 'boolean'
| 'function'
| 'null'
| 'number'
| 'object'
| 'regexp'
| 'string'
| 'symbol'
| 'undefined';

const chalk = require('chalk');

// get the type of a value with handling the edge cases like `typeof []`
// and `typeof null`
Expand All @@ -30,6 +42,9 @@ const getType = (value: any): ValueType => {
} else if (typeof value === 'string') {
return 'string';
} else if (typeof value === 'object') {
if (value.constructor === RegExp) {
return 'regexp';
}
return 'object';
// $FlowFixMe https://github.com/facebook/flow/issues/1015
} else if (typeof value === 'symbol') {
Expand Down Expand Up @@ -75,6 +90,8 @@ const stringify = (obj: any): string => {
});
};

const highlight = (obj: any) => chalk.cyan.bold(stringify(obj));

const ensureNoExpected = (expected: any, matcherName: string) => {
matcherName || (matcherName = 'This');
if (typeof expected !== 'undefined') {
Expand Down Expand Up @@ -108,10 +125,11 @@ const ensureNumbers = (actual: any, expected: any, matcherName: string) => {
};

module.exports = {
getType,
stringify,
ensureNoExpected,
ensureActualIsNumber,
ensureExpectedIsNumber,
ensureNoExpected,
ensureNumbers,
getType,
highlight,
stringify,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
exports[`.toThrowError() error class did not throw at all 1`] = `"Expected the function to throw an error of \"Err\" type, but it didn\'t."`;

exports[`.toThrowError() error class threw, but class did not match 1`] = `
"Expected the function to throw an error of \"Err2\" type, but it didn\'t.
Actual error:
Type: \"Err\"
Message: \"apple\""
`;

exports[`.toThrowError() error class threw, but should not have 1`] = `
"Expected the function to not throw an error of \"Err\" type, but it did.
Actual error:
Type: \"Err\"
Message: \"apple\""
`;

exports[`.toThrowError() regexp did not throw at all 1`] = `"Expected the function to throw an error matching \"/apple/\", but it didn\'t."`;

exports[`.toThrowError() regexp threw, but message did not match 1`] = `
"Expected the function to throw an error matching \"/banana/\", but it didn\'t.
Actual error:
Type: \"Error\"
Message: \"apple\""
`;

exports[`.toThrowError() regexp threw, but should not have 1`] = `
"Expected the function to not throw an error matching \"/apple/\", but it did.
Actual error:
Type: \"Error\"
Message: \"apple\""
`;

exports[`.toThrowError() strings did not throw at all 1`] = `"Expected the function to throw an error matching \"apple\", but it didn\'t."`;

exports[`.toThrowError() strings threw, but message did not match 1`] = `
"Expected the function to throw an error matching \"banana\", but it didn\'t.
Actual error:
Type: \"Error\"
Message: \"apple\""
`;

exports[`.toThrowError() strings threw, but should not have 1`] = `
"Expected the function to not throw an error matching \"apple\", but it did.
Actual error:
Type: \"Error\"
Message: \"apple\""
`;
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ describe('.toHaveBeenCalledTimes()', () => {
it('accept only numbers', () => {
const foo = jasmine.createSpy('foo');
foo();

expect(() => jestExpect(foo).toHaveBeenCalledTimes(1))
.not.toThrowError();
jestExpect(foo).toHaveBeenCalledTimes(1);

[{}, [], true, 'a', new Map(), () => {}].forEach(value => {
expect(() => jestExpect(foo).toHaveBeenCalledTimes(value))
Expand Down
149 changes: 149 additions & 0 deletions packages/jest-matchers/src/__tests__/toThrowMatchers-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails oncall+jsinfra
*/

'use strict';

describe('.toThrowError()', () => {
describe('strings', () => {
it('passes', () => {
expect(() => { throw new Error('apple'); }).toThrowError('apple');
expect(() => { throw new Error('banana'); }).not.toThrowError('apple');
expect(() => {}).not.toThrowError('apple');
});

test('did not throw at all', () => {
let error;
try {
expect(() => {}).toThrowError('apple');
} catch (e) {
error = e;
}

expect(error).toBeDefined();
expect(error.message).toMatchSnapshot();
});

test('threw, but message did not match', () => {
let error;
try {
expect(() => { throw new Error('apple'); }).toThrowError('banana');
} catch (e) {
error = e;
}

expect(error).toBeDefined();
expect(error.message).toMatchSnapshot();
});

test('threw, but should not have', () => {
let error;
try {
expect(() => { throw new Error('apple'); }).not.toThrowError('apple');
} catch (e) {
error = e;
}

expect(error).toBeDefined();
expect(error.message).toMatchSnapshot();
});
});

describe('regexp', () => {
it('passes', () => {
expect(() => { throw new Error('apple'); }).toThrowError(/apple/);
expect(() => { throw new Error('banana'); }).not.toThrowError(/apple/);
expect(() => {}).not.toThrowError(/apple/);
});

test('did not throw at all', () => {
let error;
try {
expect(() => {}).toThrowError(/apple/);
} catch (e) {
error = e;
}

expect(error).toBeDefined();
expect(error.message).toMatchSnapshot();
});

test('threw, but message did not match', () => {
let error;
try {
expect(() => { throw new Error('apple'); }).toThrowError(/banana/);
} catch (e) {
error = e;
}

expect(error).toBeDefined();
expect(error.message).toMatchSnapshot();
});

test('threw, but should not have', () => {
let error;
try {
expect(() => { throw new Error('apple'); }).not.toThrowError(/apple/);
} catch (e) {
error = e;
}

expect(error).toBeDefined();
expect(error.message).toMatchSnapshot();
});
});

describe('error class', () => {
class Err extends Error {}
class Err2 extends Error {}

it('passes', () => {
expect(() => { throw new Err(); }).toThrowError(Err);
expect(() => { throw new Err(); }).toThrowError(Error);
expect(() => { throw new Err(); }).not.toThrowError(Err2);
expect(() => {}).not.toThrowError(Err);
});

test('did not throw at all', () => {
let error;
try {
expect(() => {}).toThrowError(Err);
} catch (e) {
error = e;
}

expect(error).toBeDefined();
expect(error.message).toMatchSnapshot();
});

test('threw, but class did not match', () => {
let error;
try {
expect(() => { throw new Err('apple'); }).toThrowError(Err2);
} catch (e) {
error = e;
}

expect(error).toBeDefined();
expect(error.message).toMatchSnapshot();
});

test('threw, but should not have', () => {
let error;
try {
expect(() => { throw new Err('apple'); }).not.toThrowError(Err);
} catch (e) {
error = e;
}

expect(error).toBeDefined();
expect(error.message).toMatchSnapshot();
});
});
});
32 changes: 30 additions & 2 deletions packages/jest-matchers/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,15 @@ import type {
} from './types';

const matchers = require('./matchers');
const spyMatchers = require('./spy-matchers');
const spyMatchers = require('./spyMatchers');
const toThrowMatchers = require('./toThrowMatchers');

const {stringify} = require('jest-matcher-utils');

const GLOBAL_MATCHERS_OBJECT_SYMBOL = Symbol.for('$$jest-matchers-object');

class JestAssertionError extends Error {}

if (!global[GLOBAL_MATCHERS_OBJECT_SYMBOL]) {
Object.defineProperty(
global,
Expand Down Expand Up @@ -57,6 +63,8 @@ const makeThrowingMatcher = (
{args: arguments},
);

_validateResult(result);

if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR
let message = result.message;

Expand All @@ -66,7 +74,7 @@ const makeThrowingMatcher = (
message = message();
}

const error = new Error(message);
const error = new JestAssertionError(message);
// Remove this function from the stack trace frame.
Error.captureStackTrace(error, throwingMatcher);
throw error;
Expand All @@ -78,9 +86,29 @@ const addMatchers = (matchersObj: MatchersObject): void => {
Object.assign(global[GLOBAL_MATCHERS_OBJECT_SYMBOL], matchersObj);
};

const _validateResult = result => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

using an arrow function here also causes an unnecassary .bind(this) call. It'd be more efficient to use a normal function here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

true. i'd be interested in benchmarking this stuff. I don't think it's going to affect the overall performance that much though.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There aren't any unnecessary bind calls because this is run in node 4 without compiling arrow functions to functions. Also babel doesn't bind if there is no this access iirc.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:themoreyouknow: I benchmarked the arrow vs regular function in JavaScriptCore and to my surprise, arrow functions are natively faster.

normal x 53,987,644 ops/sec ±3.50% (44 runs sampled)
arrow x 57,679,587 ops/sec ±3.08% (58 runs sampled)

if (
typeof result !== 'object' ||
typeof result.pass !== 'boolean' ||
!(
typeof result.message === 'string' ||
typeof result.message === 'function'
)
) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: codestyle

typeof result.pass !== 'boolean' ||
!(
  typeof result.message === 'string' ||
  typeof result.message === 'function'
)

throw new Error(
'Unexpected return from a matcher function.\n' +
'Matcher functions should ' +
'return an object in the following format:\n' +
' {message: string | function, pass: boolean}\n' +
`'${stringify(result)}' was returned`,
);
}
};

// add default jest matchers
addMatchers(matchers);
addMatchers(spyMatchers);
addMatchers(toThrowMatchers);

module.exports = {
addMatchers,
Expand Down
Loading