app.js
class MyApp {
async fetchData() {
const response = await fetch('http://myurl.com', { method: 'GET' });
console.log(response); // received: {}, expected: { val: true }
}
}
export { MyApp };
app.test.js
import {MyApp} from "./app";
import {setupServer} from "msw/node";
import {rest} from "msw";
const server = setupServer(
rest.get('http://myurl.com', (req, res, ctx) => res(ctx.json({ val: true })))
);
describe('App', () => {
beforeAll(() => {
server.listen();
});
afterEach(() => {
server.resetHandlers();
});
afterAll(() => {
server.close();
})
it('should succeed', async () => {
const myApp = new MyApp();
await myApp.fetchData();
});
});
I have simple project, almost empty with just few files. I had to polyfill the fetch so in my setup-jest.js
file I have
global.fetch = () => Promise.resolve({});
Without that I'd get an error that the fetch is undefined. The problem is that inside fetchData
method I get the polyfill value instead of {val: true} which I defined in test file inside setupServer. Why I'm not getting the expected value?
jest.config.js
module.exports = {
setupFilesAfterEnv: ['<rootDir>/setup-jest.js']
};