Skip to content

Conversation

@rene-leanix
Copy link

This is a test-branch to check if testdouble-jest can be run with TypeScript (and the newest version of Jest).

@searls
Copy link
Member

searls commented Jun 3, 2021

I don't understand -- did you intend for this to be a PR against the main repo?

@rene-leanix
Copy link
Author

No, sorry, this was merely intended as a show case for #7. That's why I created this as a draft PR, but would have been better to create the PR just for my fork. Will close it now.

@rene-leanix rene-leanix closed this Jun 7, 2021
@RA80533
Copy link

RA80533 commented Jun 26, 2021

Use import { default as td } (or, since you have esModuleInterop enabled, import td) instead of import * as td, @rene-leanix. td will be an entirely different shape for the wildcard import—imagine it as a collection of all the exports from the module, including a default export (which is what you actually want).

Just out of curiosity, does Jest not work for your use case? It has built-in mocking, etc.

@rene-leanix
Copy link
Author

To answer your question, @RA80533, we ended up using Jest's own mocking and jest-when (with a small addition of our own to create mock return values). Here's some example code:

jest.enableAutomock();
jest.unmock('@app/spec/mocks'); // file with`when()` and other test-helpers
jest.unmock('@app/helpers'); // file to be tested

//... imports

afterAll(() => {
  jest.disableAutomock();
  cleanupWhenMocks();
});

describe('getTimeSpan()', () => {
  it('returns correct timespan based on expected function calls', () => {
    const zoomLevel = mock<TimeUnit>();
    const today = when(startOfYear).calledWith(expect.any(Date)).mockReturnValueOnce();
    const minus10Years = when(addUnits).calledWith(today, 'year', -10).mockReturnValueOnce();
    const plus10Years = when(addUnits).calledWith(today, 'year', 10).mockReturnValueOnce();
    const begin = when(getBeginOfUnit).calledWith(minus10Years, zoomLevel).mockReturnValueOnce();
    const end = when(startOfNextUnit).calledWith(plus10Years, zoomLevel).mockReturnValueOnce();

    const timespan = getTimeSpan(zoomLevel);

    expect(timespan).toStrictEqual({ unit: zoomLevel, begin, end });
  });
});

All variables in this example are mocked with a simple mock()-function that returns an otherwise object with a unique identifier. That simplifies the test a lot and makes look like the actual code a lot when it comes to function calls.

@rene-leanix rene-leanix deleted the feature/typescript-compatibility branch June 28, 2021 08:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants