Closed shishkin closed 2 years ago
The error comes with the file mock — it skips loading the real files and just returns a provided string ("test-file-stub"
in this case), which is invalid src. Adding a manual mock to the test helps:
jest.mock("../../public/logo.png", () => {
return "/public/logo.png"
})
We should fix the file mock by handling pngs
in this way that it returns an object supported by next/image (the same as in runtime):
{
type: {
blurDataURL: "data:image/png;base64,...",
height: 370,
src: "/_next/static/image/public/logo.c7cef1afc7e012994ec94fb634b8f69a.png",
width: 800
}
}
Thanks for the suggestion and triage @beerose!
The error comes with the file mock — it skips loading the real files and just returns a provided string ("test-file-stub" in this case), which is invalid src.
That relates to the second problem. But what about the error message with width and height?
I'm also not very clear why mocking is necessary for that test. Wouldn't it be beneficial to test the real image component with its source path and other attributes to e.g. verify that the source file exists?
But what about the error message with width and height?
Yeah, I forgot to include it. This mock should work:
jest.mock("../../public/logo.png", () => {
return {
default: { src: "/public/logo.png", height: 100, width: 100 },
}
})
I'm also not very clear why mocking is necessary for that test. Wouldn't it be beneficial to test the real image component with its source path and other attributes to e.g. verify that the source file exists?
I agree with you. Alternatively, you could try using jest-webpack
to make your tests more integration-like (testing webpack config and checking for actual images).
The current implementation is a suggested solution in both Next and Jest docs (they mention mocking static assets when using Jest with webpack). I guess the docs might be from before Next introduced next/image
.
To get an actual image, we'd need to use webpack in our tests. However, webpack can be slow, so I don't think we want to do it.
Suggested solution:
image-mock.js
for images and return an object that is accepted by next/image
:
{ src: "https://placekitten.com/100/100", width: 100, height: 100 }
).image-mock.js
for images in jest-preset.js
.
What is the problem?
I've enabled the skipped default test in
app/pages/index.test.tsx
and it fails. After adding the width and height attributes to the image, test keeps failing now complaining about wrong image source URL, which comes from the jest mock settings astest-file-stub
.Paste all your error logs here:
Paste all relevant code snippets here:
What are detailed steps to reproduce this?
blitz new blitzapp
app/pages/index.test.tsx
Run
blitz -v
and paste the output here:Please include below any other applicable logs and screenshots that show your problem:
URL error after fixing image width and height: