Skip to content

Commit

Permalink
Support mocking native async methods (jestjs#3209)
Browse files Browse the repository at this point in the history
* Support mocking native AsyncFunction

* Add native-async-mock example test

* Use strict

* Return a promise from mock

* Only test async

* Revert returning promise
  • Loading branch information
thymikee authored and skovhus committed Apr 29, 2017
1 parent 618eab4 commit 87f10e6
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 2 deletions.
3 changes: 3 additions & 0 deletions examples/async/native-async-mock/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["es2015"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Copyright 2004-present Facebook. All Rights Reserved.

'use strict';

jest.mock('../native');

const native = require('../native');

test('mock works with native async', () => {
expect(native.asyncMethod).toBeDefined();
});
14 changes: 14 additions & 0 deletions examples/async/native-async-mock/native.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright 2004-present Facebook. All Rights Reserved.

'use strict';

function awaitable() {
return Promise.resolve();
}

module.exports.syncMethod = () => 42;

module.exports.asyncMethod = async () => {
await awaitable();
return 42;
};
4 changes: 2 additions & 2 deletions packages/jest-mock/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ function isA(typeName: string, value: any): boolean {
}

function getType(ref?: any): string | null {
if (isA('Function', ref)) {
if (isA('Function', ref) || isA('AsyncFunction', ref)) {
return 'function';
} else if (Array.isArray(ref)) {
return 'array';
Expand Down Expand Up @@ -127,7 +127,7 @@ function isReadonlyProp(object: any, prop: string): boolean {
prop === 'callee' ||
prop === 'name' ||
prop === 'length') &&
isA('Function', object)) ||
(isA('Function', object) || isA('AsyncFunction', object))) ||
((prop === 'source' ||
prop === 'global' ||
prop === 'ignoreCase' ||
Expand Down

0 comments on commit 87f10e6

Please sign in to comment.