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

Fix babel-plugin-jest-hoist #1754

Merged
merged 3 commits into from
Sep 21, 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 @@ -27,7 +27,7 @@ if (process.platform !== 'win32') {
}

it('sucessfully runs the tests inside `babel-plugin-jest-hoist/`', () => {
const {json} = runJest.json(DIR, ['--no-cache']);
const {json} = runJest.json(DIR, ['--no-cache', '--coverage']);
expect(json.success).toBe(true);
expect(json.numTotalTestSuites).toBe(2);
});
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import e from '../__test_modules__/e';

// These will all be hoisted above imports
jest.unmock('react');
jest.unmock('../__test_modules__/Unmocked');
jest.deepUnmock('../__test_modules__/Unmocked');
jest
.unmock('../__test_modules__/c')
.unmock('../__test_modules__/d');
Expand Down Expand Up @@ -111,4 +111,10 @@ describe('babel-plugin-jest-hoist', () => {
expect(b._isMockFunction).toBe(true);
expect(b()).toEqual(undefined);
});

it('requires modules that also call jest.mock', () => {
require('../mock-file');
const mock = require('../banana');
expect(mock).toEqual('apple');
});
});
9 changes: 9 additions & 0 deletions integration_tests/babel-plugin-jest-hoist/banana.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* 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.
*/

module.exports = 'banana';
12 changes: 12 additions & 0 deletions integration_tests/babel-plugin-jest-hoist/mock-file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* 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.
*/

jest.mock('./banana', () => {
const exports = 'apple';
return exports;
});
2 changes: 1 addition & 1 deletion integration_tests/snapshot/__tests__/snapshot-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ describe('snapshot', () => {

it('cannot be used with .not', () => {
expect(() => expect('').not.toMatchSnapshot()).toThrow(
new Error('Jest: `.not` can not be used with `.toMatchSnapShot()`.')
'Jest: `.not` can not be used with `.toMatchSnapshot()`.'
);
});
});
5 changes: 4 additions & 1 deletion packages/babel-plugin-jest-hoist/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ FUNCTIONS.mock = args => {
if (!found) {
invariant(
(scope.hasGlobal(name) && WHITELISTED_IDENTIFIERS[name]) ||
/^mock/.test(name),
/^mock/.test(name) ||
// Allow istanbul's coverage variable to pass.
//^(?:__)?cov/.test(name),
'The module factory of `jest.mock()` is not allowed to ' +
'reference any out-of-scope variables.\n' +
'Invalid variable access: ' + name + '\n' +
Expand All @@ -125,6 +127,7 @@ FUNCTIONS.mock = args => {
};

FUNCTIONS.unmock = args => args.length === 1 && args[0].isStringLiteral();
FUNCTIONS.deepUnmock = args => args.length === 1 && args[0].isStringLiteral();

FUNCTIONS.disableAutomock =
FUNCTIONS.enableAutomock =
Expand Down
15 changes: 10 additions & 5 deletions packages/jest-jasmine2/src/extendJasmineExpect.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,18 @@
'use strict';

const jestExpect = require('jest-matchers').expect;
const {addMatchers} = require('jest-matchers');
const {toMatchSnapshot} = require('jest-snapshot');

const jasmineExpect = global.expect;

// extend jasmine matchers with `jest-matchers`
global.expect = actual => {
const jasmineMatchers = jasmineExpect(actual);
const jestMatchers = jestExpect(actual);
const not = Object.assign(jasmineMatchers.not, jestMatchers.not);
return Object.assign(jasmineMatchers, jestMatchers, {not});
module.exports = () => {
addMatchers({toMatchSnapshot});
global.expect = actual => {
const jasmineMatchers = jasmineExpect(actual);
const jestMatchers = jestExpect(actual);
const not = Object.assign(jasmineMatchers.not, jestMatchers.not);
return Object.assign(jasmineMatchers, jestMatchers, {not});
};
};
18 changes: 6 additions & 12 deletions packages/jest-jasmine2/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import type Runtime from 'jest-runtime';
const JasmineReporter = require('./reporter');

const jasmineAsync = require('./jasmine-async');
const snapshot = require('jest-snapshot');
const fs = require('graceful-fs');
const path = require('path');
const vm = require('vm');
Expand Down Expand Up @@ -101,14 +100,6 @@ function jasmine2(
);

env.beforeEach(() => {
jasmine.addMatchers({
toMatchSnapshot: snapshot.matcher(
testPath,
config,
snapshotState,
),
});

if (config.resetModules) {
runtime.resetModules();
}
Expand All @@ -118,16 +109,19 @@ function jasmine2(
}
});

const snapshotState = snapshot.getSnapshotState(jasmine, testPath);

env.addReporter(reporter);

// `jest-matchers` should be required inside test environment (vm).
// Otherwise if they throw, the `Error` class will differ from the `Error`
// class of the test and `error instanceof Error` will return `false`.
runtime.requireInternalModule(
path.resolve(__dirname, './extendJasmineExpect.js'),
);
)();

const snapshotState = runtime.requireInternalModule(
path.resolve(__dirname, './setup-jest-globals.js'),
)({testPath, config});


if (config.setupTestFrameworkScriptFile) {
runtime.requireModule(config.setupTestFrameworkScriptFile);
Expand Down
79 changes: 79 additions & 0 deletions packages/jest-jasmine2/src/setup-jest-globals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* 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.
*
* @flow
*/

'use strict';

import type {Config, Path} from 'types/Config';

const {getState, setState} = require('jest-matchers');
const {initializeSnapshotState} = require('jest-snapshot');

// Get suppressed errors form jest-matchers that weren't throw during
// test execution and add them to the test result, potentially failing
// a passing test.
const addSuppressedErrors = result => {
const {suppressedErrors} = getState();
setState({suppressedErrors: []});
if (suppressedErrors.length) {
result.status = 'failed';

result.failedExpectations = suppressedErrors.map(error => ({
message: error.message,
stack: error.stack,
passed: false,
expected: '',
actual: '',
}));
}
};

const patchJasmine = () => {
global.jasmine.Spec = (realSpec => {
const Spec = function Spec(attr) {
const resultCallback = attr.resultCallback;
attr.resultCallback = function(result) {
addSuppressedErrors(result);
resultCallback.call(attr, result);
};

const onStart = attr.onStart;
attr.onStart = context => {
setState({currentTestName: context.getFullName()});
onStart && onStart.call(attr, context);
};

realSpec.call(this, attr);
};

Spec.prototype = realSpec.prototype;
for (const statics in realSpec) {
if (Object.prototype.hasOwnProperty.call(realSpec, statics)) {
Spec[statics] = realSpec[statics];
}
}
return Spec;

})(global.jasmine.Spec);
};

type Options = {
testPath: Path,
config: Config,
};

module.exports = ({testPath, config}: Options) => {
setState({testPath});
patchJasmine();
const snapshotState
= initializeSnapshotState(testPath, config.updateSnapshot);
setState({snapshotState});
// Return it back to the outer scope (test runner outside the VM).
return snapshotState;
};
Loading