I'm trying to use MSW to mock my server side calls to Stripe in my integration tests.
The code is pretty straight forward:
// @vitest-environment node
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { describe, expect, test } from 'vitest';
import {
mockStripePrices,
mockStripeProducts,
} from '~/test/mocks/fixtures/stripe';
import { fetchProductsWithPrices } from './billing-helpers.server';
const server = setupServer(
rest.get('https://api.stripe.com/v1/products', (request, response, context) =>
response(context.json(mockStripeProducts)),
),
rest.get('https://api.stripe.com/v1/prices', (request, response, context) =>
response(context.json(mockStripePrices)),
),
);
beforeAll(() => server.listen({ onUnhandledRequest: 'warn' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
describe('fetchProductsWithPrices()', () => {
test('given nothing: returns all our products and their prices', async () => {
const actual = await fetchProductsWithPrices();
const expected = [];
expect(actual).toEqual(expected);
});
});
Where fetchProductsWithPrices
is:
import { stripeAdmin } from './stripe-admin.server';
export async function fetchProductsWithPrices() {
const [products, prices] = await Promise.all([
stripeAdmin.products.list({ active: true }),
stripeAdmin.prices.list({ active: true }),
]);
return products.data.map(product => ({
...product,
prices: prices.data.filter(price => price.product === product.id),
}));
}
Somehow the real data is coming through, and NOT the mocks. (So my function works as expected, but MSW should catch the requests and return the mock data instead of my real data).
What is going wrong? Is it maybe a simple typo that I can't find?
I was under the impression that the Node.js Stripe library is simply a wrapper around Stripe's REST API, but just to make sure I wasn't tripping I also tried mocking graphql:
const stripe = graphql.link('https://api.stripe.com/v1/');
But that didn't work neither.
What am I doing wrong?
This was a bug in Stripe that will be fixed in an upcoming version: https://github.com/stripe/stripe-node/issues/1844#issuecomment-1648451436