Ömer Keskinkilic
Ömer Keskinkilic

Reputation: 83

How to skip mocked image and get real image attributes with Jest?

I am writing unit tests and I want to test an img atrributes. However, when I make an assertion, I get mocked img attributes which is under __mocks__>fileMock.js. Because I mock files, I only get mocked file atrributes. How can I skip mocked files in my tests?

describe('Buttons', () => {

test('Clear filters work after filtering tools, workflows and using searchbar', async () => {
    render(<HeaderBar {...defaults} />);

    const clearFilterButton = screen.getByRole('button', { name: 'Clear Filters' });
    const toolsButton = screen.getByRole('button', { name: 'TOOLS' });
    const selectedTools = await within(toolsButton).findByRole('img');
    expect(selectedTools).toHaveAttribute('src', 'images/tools-selected.png');

});

And test result is :

 Buttons › Clear filters work after filtering tools, workflows and using searchbar

expect(element).toHaveAttribute("src", "images/tools-selected.png") // element.getAttribute("src") === "images/tools-selected.png"

Expected the element to have attribute:
  src="images/tools-selected.png"
Received:
  src="test-file-stub"

  39 |         const toolsButton = screen.getByRole('button', { name: 'TOOLS' });
  40 |         const selectedTools = await within(toolsButton).findByRole('img');
> 41 |         expect(selectedTools).toHaveAttribute('src', 'images/tools-selected.png');

I need to test real image, and skip mocking that img in my test.

Upvotes: 1

Views: 672

Answers (1)

Brian Adams
Brian Adams

Reputation: 45850

It sounds like you have a manual user module mock defined in a __mock__ folder next to your actual code.

In that case the mock is used in any test file where you call jest.mock('moduleName') unless automock is set to true in which case the mock will always be used.

If you are explicitly mocking the file using jest.mock('moduleName') then simply remove that from the test file where you want to use the actual code instead of the mock.

If you have automock set to true in your Jest config then you can tell Jest to use the original code file in a given test by using jest.unmock('moduleName').

Upvotes: 1

Related Questions