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

Added support for naming mocked functions #4586

Merged
merged 18 commits into from
Oct 8, 2017

Conversation

gricard
Copy link
Contributor

@gricard gricard commented Oct 2, 2017

Summary

This patch adds the ability to specify a name for a just.fn() mock, so if the test fails, you will see that name in the error output instead of "just.fn()", which should help make some test results clearer. It provides a few different ways to specify the mock name.

Motivation

I switched a frontend product over to Jest from Karma/Mocha/Chai a few months ago, and I love it. But there's a couple things that I wanted to see in the output, like specified mock names, and I did not see any existing means to add that to my tests.

Test plan

Unit tests and integration tests have been added.

@codecov-io
Copy link

codecov-io commented Oct 2, 2017

Codecov Report

Merging #4586 into master will decrease coverage by <.01%.
The diff coverage is 50%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #4586      +/-   ##
==========================================
- Coverage   55.68%   55.67%   -0.01%     
==========================================
  Files         186      186              
  Lines        6348     6356       +8     
  Branches        3        3              
==========================================
+ Hits         3535     3539       +4     
- Misses       2812     2816       +4     
  Partials        1        1
Impacted Files Coverage Δ
packages/jest-mock/src/index.js 83.88% <50%> (-1.03%) ⬇️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 7aa3017...b303876. Read the comment docs.

@SimenB
Copy link
Member

SimenB commented Oct 6, 2017

@gricard You can add an integration test, there you can get both stdout and stderr. Lots of examples in there

@gricard
Copy link
Contributor Author

gricard commented Oct 6, 2017

Thanks, @SimenB.

@gricard
Copy link
Contributor Author

gricard commented Oct 6, 2017

Interesting... AppVeyor build failed, and it looks like it's because the snapshot tests failed due to slight differences in the characters used. Should I not have committed the snapshots created on my Mac? That appears to be the problem. Output differences between macOS / Windows.

    Received value does not match stored snapshot 1.
    
    - Snapshot
    + Received
    
    - "PASS __tests__/index.js
    -   ✓ first test
    + "PASS __tests__\\index.js
    +   √ first test
      
      "

@gricard
Copy link
Contributor Author

gricard commented Oct 7, 2017

Well, if the test output varies by platform, then I'll do regex matching instead

@SimenB
Copy link
Member

SimenB commented Oct 7, 2017

You can do skipOnWindows, not sure if that's wanted here, though

@@ -138,13 +138,32 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
> 'first call', 'second call', 'default', 'default'
```

### `mockFn.mockReturnThis()`
Copy link
Member

Choose a reason for hiding this comment

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

why is this removed?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Looks like an accident on my part. I'll fix it.

test('first test', () => {
mockFn();
expect(mockFn).toHaveBeenCalled();
expect(mockFn.mock.calls.length).toBe(1);
Copy link
Member

@SimenB SimenB Oct 7, 2017

Choose a reason for hiding this comment

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

any particular reason why you do this instead of expect(mockFn).toHaveBeenCalledTimes(1)?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No reason. I just copied what was in another test suite in there that I based mine on.

@@ -0,0 +1,70 @@
/**
Copy link
Member

@SimenB SimenB Oct 7, 2017

Choose a reason for hiding this comment

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

Can you add a test for failing expect(mockWithName).not.toHaveBeenCalled() and expect(mockWithName).toHaveBeenCalledTimes(5) to assert on the name for them as well? I see no reason for them not to work as you expect, but having the assertions would be nice

Copy link
Contributor Author

Choose a reason for hiding this comment

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

So, a test where the assertion expect(mockWithName).not.toHaveBeenCalled() will fail, and then check for that error?

And a test for expect(mockWithName).toHaveBeenCalledTimes(5) when it's not called 5 times?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ok, I've added more tests to cover those.

Copy link
Member

Choose a reason for hiding this comment

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

Yup. Thanks!

@cpojer
Copy link
Member

cpojer commented Oct 7, 2017

I quite like it. Thanks for contributing this change to Jets. However, I'd prefer to not add an argument to jest.fn at this point. Could we change this PR to only add .mockName? Thank you.

@gricard
Copy link
Contributor Author

gricard commented Oct 8, 2017

Whatever floats your boat.

…fn() and only use jest.fn().mockName() to set it
Remove obsolete unit tests
@gricard
Copy link
Contributor Author

gricard commented Oct 8, 2017

Hm. Well, I made the changes, but circleci test-node-8 is failing because of an unrelated test failure.

 FAIL  integration_tests/__tests__/transform.test.js (24.846s)
  ● babel-jest › runs transpiled code

    
          ORIGINAL CMD: yarn
          STDOUT: 
          STDERR: warning package.json: No license field
    warning ../../package.json: No license field
    warning No license field
    error An unexpected error occurred: "https://registry.yarnpkg.com/core-js/-/core-js-2.4.1.tgz: Request failed \"530 undefined\"".
    
          STATUS: 1
          ERROR: undefined
      
          
      at run (integration_tests/utils.js:33:11)
      at Object.beforeEach (integration_tests/__tests__/transform.test.js:28:7)
          at Promise (<anonymous>)
          at <anonymous>

@SimenB
Copy link
Member

SimenB commented Oct 8, 2017

Restarted it, and CI is happy now

@gricard
Copy link
Contributor Author

gricard commented Oct 8, 2017

Sweet. Thanks, dude.

@SimenB
Copy link
Member

SimenB commented Oct 8, 2017

Question: Is the name cleared by calling mock.mockReset()? Should it be?

@gricard
Copy link
Contributor Author

gricard commented Oct 8, 2017

Ooh. Yeah. That makes sense. I didn't think of that. I can change it so that clears out the name also.

@SimenB
Copy link
Member

SimenB commented Oct 8, 2017

I think it should mockReset and mockRestore should clear it, but not mockClear.

@gricard
Copy link
Contributor Author

gricard commented Oct 8, 2017

I took a look at the docs for all of those. I think only mockReset() makes sense, in terms of clearing out the name. mockRestore() is specific to the mocked implementation.

@cpojer
Copy link
Member

cpojer commented Oct 8, 2017

Yep, agreed. :)

@gricard
Copy link
Contributor Author

gricard commented Oct 8, 2017

It looks like mockReset() already does this, because it clears out the mock entirely with its config (where the mock name is stored). I've added a unit test to verify this, and updated the documentation for mockReset().

@SimenB
Copy link
Member

SimenB commented Oct 8, 2017

For funsies, can you add a test that verifies that mock{Clear,Restore} does not clear the name?

(I always have to check the docs for the purpose of the 3 different resets, so having super explicit tests is a good thing I think).

It should be good to merge either way, this is awesome! Gonna start using it as soon as it's released 🙂

@gricard
Copy link
Contributor Author

gricard commented Oct 8, 2017

All set, @SimenB

@gricard
Copy link
Contributor Author

gricard commented Oct 8, 2017

And thanks! I really like Jest and this will help me out a lot as well. Hopefully I can contribute some more to the project. :)

Copy link
Member

@SimenB SimenB left a comment

Choose a reason for hiding this comment

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

LGTM (pending CI). Thanks for sticking around for our nit-picking

@cpojer
Copy link
Member

cpojer commented Oct 8, 2017

Alright, I think this is almost good to go, I would just like to request one more change (sorry :( ). Could we split the function up into mockName as a setter and getMockName to get the value? I generally don't like functions that behave differently based on the amount of arguments. Thank you.

… getMockName() instead of overloading mockName() function to return it when no arguments are passed
@gricard
Copy link
Contributor Author

gricard commented Oct 8, 2017

All set

@cpojer cpojer merged commit efe65d4 into jestjs:master Oct 8, 2017
@cpojer
Copy link
Member

cpojer commented Oct 8, 2017

Thanks for sticking with us, this is a great PR :)

@gricard
Copy link
Contributor Author

gricard commented Oct 8, 2017

Thanks, dude!

.mockImplementation(scalar => 42 + scalar)
.mockName('add42');

const myMockFn2 = jest.fn(scalar => 42 + scalar, 'add42');
Copy link
Member

Choose a reason for hiding this comment

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

this is wrong now

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Damn. I thought I caught all the doc references. Can I still commit changes for this PR, or is that done since it's merged?

Copy link
Member

Choose a reason for hiding this comment

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

New PR is needed

@@ -217,6 +217,19 @@ const otherObj = {
};
```

## Mock Names
Copy link
Member

Choose a reason for hiding this comment

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

should it include a "availble in jest 21.4" or something?

@github-actions
Copy link

This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 13, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants