Unable to properly mock API calls using Jest - javascript

I have been trying to mock my apis using jest.mock() but I cant even get jest to call these apis normally.
I have been able to successfully mock the the function and then mock the api like this:
wrapper.vm.getUser = jest.fn(() => Promise.resolve({}));
but I would like to mock all the apis in api/authApis.js directly instead of intercepting them at the function.
I cant do it because this.$apis is showing up as undefined.
How do I access and call this.$apis.getUser() using Jest?
tests/header.spec.js
import { mount } from "#vue/test-utils";
import Header from "../components/Header.vue";
describe("Header", () => {
it("returns the val from api", async () => {
//setting multiUser true so button is visible
const multiUsers = true;
const wrapper = mount(Header, {
propsData: {
multiUsers
}
});
console.log(wrapper.vm.getUser());
const changeUsrBtn = wrapper.find("#btnChangeUser");
//triggering the user btn with a click
changeUsrBtn.trigger("click");
expect(wrapper.find("button").text()).toBe("Change User");
expect(wrapper.vm.getUser()).toHaveReturned();
});
});
The error:
FAIL __tests__/header.spec.js
Header
× returns the val from api (122 ms)
● Header › returns the val from api
expect(received).toHaveReturned()
Matcher error: received value must be a mock function
Received has type: object
Received has value: {}
23 | expect(wrapper.find("button").text()).toBe("Change User");
24 |
> 25 | expect(wrapper.vm.getUser()).toHaveReturned();
| ^
26 |
27 | });
28 | });
at Object.<anonymous> (__tests__/header.spec.js:25:36)
at TestScheduler.scheduleTests (node_modules/#jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/#jest/core/build/runJest.js:387:19)
at _run10000 (node_modules/#jest/core/build/cli/index.js:408:7)
at runCLI (node_modules/#jest/core/build/cli/index.js:261:3)
console.error
TypeError: Cannot read property 'authService' of undefined
components/Header.vue
async getUser() {
this.showUserLoader = true;
try {
const {
data: { userList }
} = await
this.$apis.authService.getUser();
this.$store.dispatch("auth/updateUsers", UserList);
} catch (error) {
console.error(error);
} finally {
this.showUserLoader = false;
}
}
...
api/authApis.js (I would like to mock this entire file):
export default $axios => ({
getUser() {
return $axios({
url_instance: authInstance,
method: "get",
url_suffix: "/sc/typesOfUser",
});
},
changeUser() {
return $axios({
url_instance: authInstance,
method: "post",
url_suffix: "/sc/changeUser"
});
},
...
})

It depends on how you set the global this.$api, but if you want to mock an entire file (especially using the default export), you should use the __esModule property:
jest.mock('./esModule', () => ({
__esModule: true, // this property makes it work
default: 'mockedDefaultExport',
namedExport: jest.fn(),
}));
More explanations on Jest mock default and named export.

Related

Mocking es6 class static methods with Jest

I am really having big trouble handling this issue. I have read Jest docs a lot, also other articles, but nothing has helped me yet, even chatGPT.
I am trying to test this class.
export class CookiesManager extends Auth {
static get(key: string) {
return this.cookies.get(key);
}
static set(key: string, value: any, config?: CookieSetOptions) {
this.cookies.set(key, value, config || this.config);
}
static remove(key: string) {
const { hostname } = new URL(`${process.env.WEB_HOST}`);
this.cookies.remove(key, { ...this.config, domain: hostname });
}
}
Here is the Auth class, but in my case, I haven't even reached here or I guess I will not need to handle that part in the scope of this one. Anyway, just for a reference.
import moment from 'moment';
import Cookies, { CookieSetOptions } from 'universal-cookie';
export class Auth {
static cookies = new Cookies();
static config: CookieSetOptions = {
path: '/',
maxAge: 1800,
expires: moment().add(30, 'm').toDate(),
secure: process.env.NODE_ENV !== 'development',
};
static setToken(token: string) {
token && this.cookies.set('auth_token', token, this.config);
}
static getToken() {
return this.cookies.get('auth_token');
}
static clear() {
this.cookies.remove('auth_token', this.config);
}
}
I have written the mock for the CookiesManager class.The module has also other named exports.
jest.mock('core/utils/storage-manager.ts', () => {
const originalClasses = jest.requireActual('core/utils/storage-manager.ts');
class CookiesManagerMock {
static config = {
path: '/',
maxAge: 1800,
}
static set = jest.fn().mockImplementation((key, value, config) => {
console.log('Mock set called');
mockCookies[key] = value;
})
static get = jest.fn().mockImplementation((key) => {
console.log('Mock get called');
return mockCookies[key];
})
static remove = jest.fn().mockImplementation((key, config) => {
console.log('Mock remove called');
delete mockCookies[key];
})
}
return {
...originalClasses,
CookiesManager: CookiesManagerMock,
}
})
This is the test block.
describe('CookiesManager', () => {
afterEach(() => {
jest.restoreAllMocks();
});
test('It should set a cookie', () => {
CookiesManager.set('test_key', 'test_value');
console.log(mockCookies.test_key, 'mockCookies')
expect(CookiesManager.set).toHaveBeenCalledWith('test_key', 'test_value');
});
test('It should get a cookie', () => {
CookiesManager.get.mockReturnValueOnce('test_value');
expect(CookiesManager.get('test_key')).toEqual('test_value');
expect(CookiesManager.get).toHaveBeenCalledWith('test_key');
});
test('It should remove a cookie', () => {
CookiesManager.remove('test_key');
expect(CookiesManager.remove).toHaveBeenCalledWith('test_key');
});
})
UPDATED
Even though the tests are passing, non of the console.log statements are being called in mocked class. And also mockCookies is always empty. I have tried the same with CommonJS modules and the strange thing is that console.log statements are being called.
In Jest docs, it's clearly stated.
mockFn.mockImplementation(fn)
Accepts a function that should be used as the implementation of the
mock. The mock itself will still record all calls that go into and
instances that come from itself – the only difference is that the
implementation will also be executed when the mock is called.
Maybe I am getting something wrong and don't understand the nature of the mocks.
You didn't mock the static methods correctly. The way you are using is trying to mock the instance methods of a class. Here is a solution, create a mock CookiesManager class with mock static methods.
storage-manager.ts:
type CookieSetOptions = any;
export class CookiesManager {
static get(key: string) {}
static set(key: string, value: any, config?: CookieSetOptions) {}
static remove(key: string) {}
}
export const a = () => 'a'
export const b = () => 'b'
storage-manager.test.ts:
import { CookiesManager, a, b } from './storage-manager';
jest.mock('./storage-manager', () => {
const originalModules = jest.requireActual('./storage-manager');
const mockCookies = {};
class CookiesManagerMock {
static set = jest.fn().mockImplementation((key, value, config) => {
console.log('Mock set called');
mockCookies[key] = value;
});
static get = jest.fn().mockImplementation((key) => {
console.log('Mock get called');
return mockCookies[key];
});
static remove = jest.fn().mockImplementation((key, config) => {
console.log('Mock remove called');
delete mockCookies[key];
});
}
return {
...originalModules,
CookiesManager: CookiesManagerMock,
};
});
describe('75323871', () => {
test('It should set a cookie', () => {
const config = { path: '/', maxAge: 1800 };
expect(jest.isMockFunction(CookiesManager.set)).toBeTruthy();
CookiesManager.set('test_key', 'test_value', config);
expect(CookiesManager.set).toHaveBeenCalledWith('test_key', 'test_value', config);
expect(CookiesManager.get('test_key')).toBe('test_value');
// other named exports
expect(a()).toBe('a');
expect(b()).toBe('b');
});
});
jest.config.js:
module.exports = {
preset: 'ts-jest/presets/js-with-ts'
};
Test result:
PASS stackoverflow/75323871/storage-manager.test.ts (8.614 s)
75323871
✓ It should set a cookie (17 ms)
console.log
Mock set called
at Function.<anonymous> (stackoverflow/75323871/storage-manager.test.ts:9:15)
console.log
Mock get called
at Function.<anonymous> (stackoverflow/75323871/storage-manager.test.ts:14:15)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.358 s, estimated 10 s
Note: Maybe jest.spyOn(CookiesManager, 'set').mockImplementation() is a better solution, you only need to mock the specific static method. see https://jestjs.io/docs/es6-class-mocks#static-getter-and-setter-methods
package version:
"jest": "^26.6.3",
"ts-jest": "^26.4.4"

Redux-Saga failing error handling tests using Generator.prototype.next()

I am visiting an old project and ran the tests. However, testing my Redux-Saga is not passing its error handling tests.
All The other tests are passing without problem so I know the functions are being called correctly. Below is the test file
import { takeLatest, call, put } from 'redux-saga/effects'
import { firestore, convertCollectionsSnapshotToMap } from '../../firebase/firebase.utils'
import { fetchCollectionsSuccess, fetchCollectionsFailure } from './shop.actions'
import ShopActionTypes from './shop.types'
import { fetchCollectionsAsync, fetchCollectionsStart } from './shop.sagas'
describe('fetch collections start saga', () => {
it('should trigger on FETCH_COLLECTIONS_START', () => {
const generator = fetchCollectionsStart()
expect(generator.next().value).toEqual(
takeLatest(ShopActionTypes.FETCH_COLLECTIONS_START, fetchCollectionsAsync)
)
})
})
describe('fetch collections async saga', () => {
const generator = fetchCollectionsAsync()
it('should call firestore collection ', () => {
const getCollection = jest.spyOn(firestore, 'collection')
generator.next()
expect(getCollection).toHaveBeenCalled()
})
it('should call convertCollectionsSnapshot saga ', () => {
const mockSnapshot = {}
expect(generator.next(mockSnapshot).value).toEqual(
call(convertCollectionsSnapshotToMap, mockSnapshot)
)
})
it('should fire fetchCollectionsSuccess if collectionsMap is succesful', () => {
const mockCollectionsMap = {
hats: { id: 1 }
}
expect(generator.next(mockCollectionsMap).value).toEqual(
put(fetchCollectionsSuccess(mockCollectionsMap))
)
})
// THIS IS THE FAILING CODE
it('should fire fetchCollectionsFailure if get collection fails at any point', () => {
const newGenerator = fetchCollectionsAsync()
newGenerator.next()
expect(newGenerator.throw({ message: 'error' }).value).toEqual(
put(fetchCollectionsFailure('error'))
)
})
})
Below is my shop Saga.js file
import { takeLatest, call, put, all } from 'redux-saga/effects'
import { firestore, convertCollectionsSnapshotToMap } from '../../firebase/firebase.utils'
import { fetchCollectionsSuccess, fetchCollectionsFailure } from './shop.actions'
import ShopActionTypes from './shop.types'
export function* fetchCollectionsAsync() {
try {
const collectionRef = firestore.collection('collections')
const snapshot = yield collectionRef.get()
const collectionsMap = yield call(convertCollectionsSnapshotToMap, snapshot)
yield put(fetchCollectionsSuccess(collectionsMap))
} catch (error) {
yield put(fetchCollectionsFailure(error.message))
}
}
export function* fetchCollectionsStart() {
yield takeLatest(ShopActionTypes.FETCH_COLLECTIONS_START, fetchCollectionsAsync)
}
export function* shopSagas() {
yield all([call(fetchCollectionsStart)])
}
I have tried mocking the error and passing it into my tests also but I am getting the same output in my tests below, no matter how I refactor the code.
PASS src/pages/checkout/checkout.test.js
FAIL src/redux/shop/shop.sagas.test.js
● fetch collections async saga › should fire fetchCollectionsFailure if get collection fails at any point
error
Test Suites: 1 failed, 1 passed, 2 total
Tests: 1 failed, 5 passed, 6 total
Snapshots: 1 passed, 1 total
Time: 3.076 s
Ran all test suites related to changed files
If anyone has any advice on where to look and how to fix this, it would be greatly appreciated. Thanks in advance
I have written the following code as a workaround. Tests are now passing and the fetchCollectionsFailure is being called. It's not the prettiest code but it's a workaround and fulfills the criteria for now.
it('should fire fetchCollectionsFailure if get collection fails at any point', () => {
const newGenerator = fetchCollectionsAsync()
const error = {
'##redux-saga/IO': true,
combinator: false,
payload: {
action: {
payload: "Cannot read property 'get' of undefined",
type: 'FETCH_COLLECTIONS_FAILURE'
},
channel: undefined
},
type: 'PUT'
}
expect(newGenerator.next().value).toMatchObject(error)
})

Getting error: Test webhook error: 400 when trying to send a test event to a webhook endpoint

I am attempting to send a test webhook as instructed in this tutorial.
But when I go to do it I get the error seen in the first link, and below:
Test webhook error: 400
Here is my index.ts code & functions I have deployed to firebase functions.
import * as functions from 'firebase-functions';
​
​
// const functions = require('firebase-functions');
const stripe = require('stripe')(functions.config().keys.webhooks);
const admin = require('firebase-admin');
​
admin.initializeApp();
const endpointSecret = functions.config().keys.signing;
​
exports.events = functions.https.onRequest((request, response) => {
​
let sig = request.headers["stripe-signature"];
​
try {
let event = stripe.webhooks.constructEvent(request.rawBody, sig, endpointSecret); // Validate the request
return admin.database().ref('/events').push(event) // Add the event to the database
.then((snapshot: { ref: { toString: () => any; }; }) => {
// Return a successful response to acknowledge the event was processed successfully
return response.json({ received: true, ref: snapshot.ref.toString() });
})
.catch((err: any) => {
console.error(err) // Catch any errors saving to the database
return response.status(500).end();
});
}
catch (err) {
return response.status(400).end(); // Signing signature failure, return an error 400
}
});
​
exports.exampleDatabaseTrigger = functions.database.ref('/events/{eventId}').onCreate((snapshot, context) => {
return console.log({
eventId: context.params.eventId,
data: snapshot.val()
});
});
How do I fix this and successfully run the test?
My current thinking is that the problem may have something to do with:
How I wrote this line: snapshot: { ref: { toString: () => any; };
Update:
From my testing, this does not appear to be the case.
I don't believe that the 'test webhook' properly signs them; you should use Stripe CLI for this instead.

Mocking function object with jest

I currently have an object that is used to interact with my API api.js:
export var Auth = (function () {
var Login = async function(username, password) {
//Async login code for interacting with the API
};
return {
Login: Login
}
});
And this object is imported inside another file, login.js:
import * as API from './api';
export var LoginRequestHandler = function() {
//processess user input, then calls:
try {
await API.Auth().Login(username, password);
} catch(e) {
throw new Error(e);
}
This is my jest test:
import * as API from '../api';
import * as User from '../user';
jest.mock('../api');
const spy = jest.spyOn(API.Auth(), 'Login');
User.LoginRequestHandler().then(() => {
expect(spy).toHaveBeenLastCalledWith('theUsername', 'thePassword');
}).catch(error => console.log(error));
This is my mock file, __mock__/api.js:
export var Auth = (function () {
var Login = async function(username, password) {
return Promise.resolve(true);
};
return {
Login: Login
}
});
I retrieve theUsername and thePassword through document.getElementId() in the LoginRequestHandler and create my own DOM for the test above.
Adding console.log(username) in the LoginRequestHandler reveals that it is being called and is able to get the right values. Furthermore, adding a console.log(username) in API.Auth().Login also reveals that it is getting the right values as well. However, when I look at my test logs, I see: Number of calls: 0 for the mock function and the test results in errors.
I assume that I am trying to spy on the wrong function, and is there anyway that I can fix this?
Every time you call API.Auth(), it will return a new object which has a Login method. So, the object created in LoginRequestHandler function and created by jest.spyOn(API.Auth(), 'Login') statement in your test case are different. The spy is only added to the later one. The Login method in LoginRequestHandler function is not spied.
So, here I am going to use jest.mock() to mock the api.js module without putting mocked object to __mocks__ directory. E.g.
api.js:
export var Auth = function () {
var Login = async function (username, password) {};
return {
Login: Login,
};
};
user.js:
import * as API from './api';
export var LoginRequestHandler = async function () {
const username = 'theUsername';
const password = 'thePassword';
try {
await API.Auth().Login(username, password);
} catch (e) {
throw new Error(e);
}
};
user.test.js:
import * as API from './api';
import * as User from './user';
jest.mock('./api', () => {
const auth = { Login: jest.fn() };
return {
Auth: jest.fn(() => auth),
};
});
describe('61643983', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should login', () => {
expect.assertions(2);
return User.LoginRequestHandler().then(() => {
expect(API.Auth).toBeCalledTimes(1);
expect(API.Auth().Login).toHaveBeenLastCalledWith('theUsername', 'thePassword');
});
});
it('should throw error', () => {
expect.assertions(4);
const mError = new Error('user not found');
API.Auth().Login.mockRejectedValueOnce(mError);
return User.LoginRequestHandler().catch((e) => {
expect(API.Auth).toBeCalled();
expect(API.Auth().Login).toHaveBeenLastCalledWith('theUsername', 'thePassword');
expect(e).toBeInstanceOf(Error);
expect(e.message).toMatch(/user not found/);
});
});
});
unit test results with 100% coverage:
PASS stackoverflow/61643983/user.test.js (11.507s)
61643983
✓ should login (5ms)
✓ should throw error (3ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
user.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 13.023s
source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61643983

How do I test axios in Jest?

I have this action in React:
export function fetchPosts() {
const request = axios.get(`${WORDPRESS_URL}`);
return {
type: FETCH_POSTS,
payload: request
}
}
How do I test Axios in this case?
Jest has this use case on their site for asynchronous code where they use a mock function, but can I do this with Axios?
Reference: An Async Example
I have done this so far to test that it is returning the correct type:
it('should dispatch actions with the correct type', () => {
store.dispatch(fetchPosts());
let action = store.getActions();
expect(action[0].type).toBe(FETCH_POSTS);
});
How can I pass in mock data and test that it returns?
Without using any other libraries:
import * as axios from "axios";
// Mock out all top level functions, such as get, put, delete and post:
jest.mock("axios");
// ...
test("good response", () => {
axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));
// ...
});
test("bad response", () => {
axios.get.mockImplementation(() => Promise.reject({ ... }));
// ...
});
It is possible to specify the response code:
axios.get.mockImplementation(() => Promise.resolve({ status: 200, data: {...} }));
It is possible to change the mock based on the parameters:
axios.get.mockImplementation((url) => {
if (url === 'www.example.com') {
return Promise.resolve({ data: {...} });
} else {
//...
}
});
Jest v23 introduced some syntactic sugar for mocking Promises:
axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));
It can be simplified to
axios.get.mockResolvedValue({ data: {...} });
There is also an equivalent for rejected promises: mockRejectedValue.
Further Reading:
Jest mocking documentation
A GitHub discussion that explains about the scope of the jest.mock("axios") line.
A related question which addresses applying the techniques above to Axios request interceptors.
Using jest functions like mockImplementation in TypeScript: Typescript and Jest: Avoiding type errors on mocked functions
I used axios-mock-adapter.
In this case the service is described in ./chatbot.
In the mock adapter you specify what to return when the API endpoint is consumed.
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';
describe('Chatbot', () => {
it('returns data when sendMessage is called', done => {
var mock = new MockAdapter(axios);
const data = { response: true };
mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);
chatbot.sendMessage(0, 'any').then(response => {
expect(response).toEqual(data);
done();
});
});
});
You can see it the whole example here:
Service:
https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js
Test:
https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js
I could do that following the steps:
Create a folder __mocks__/ (as pointed by #Januartha comment)
Implement an axios.js mock file
Use my implemented module on test
The mock will happen automatically
Example of the mock module:
module.exports = {
get: jest.fn((url) => {
if (url === '/something') {
return Promise.resolve({
data: 'data'
});
}
}),
post: jest.fn((url) => {
if (url === '/something') {
return Promise.resolve({
data: 'data'
});
}
if (url === '/something2') {
return Promise.resolve({
data: 'data2'
});
}
}),
create: jest.fn(function () {
return this;
})
};
Look at this
The function to test album.js
const fetchAlbum = function () {
return axios
.get("https://jsonplaceholder.typicode.com/albums/2")
.then((response) => {
return response.data;
});
};
The test album.test.js
const axios = require("axios");
const { fetchAlbum } = require("../utils.js");
jest.mock("axios");
test("mock axios get function", async () => {
expect.assertions(1);
const album = {
userId: 1,
id: 2,
title: "sunt qui excepturi placeat culpa",
};
const payload = { data: album };
// Now mock axios get method
axios.get = jest.fn().mockResolvedValue(payload);
await expect(fetchAlbum()).resolves.toEqual(album);
});
I've done this with nock, like so:
import nock from 'nock'
import axios from 'axios'
import httpAdapter from 'axios/lib/adapters/http'
axios.defaults.adapter = httpAdapter
describe('foo', () => {
it('bar', () => {
nock('https://example.com:443')
.get('/example')
.reply(200, 'some payload')
// test...
})
})
For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:
File actions.test.js:
describe('SignInUser', () => {
var history = {
push: function(str) {
expect(str).toEqual('/feed');
}
}
it('Dispatches authorization', () => {
let mock = new MockAdapter(axios);
mock.onPost(`${ROOT_URL}/auth/signin`, {
email: 'test#test.com',
password: 'test'
}).reply(200, {token: 'testToken' });
const expectedActions = [ { type: types.AUTH_USER } ];
const store = mockStore({ auth: [] });
return store.dispatch(actions.signInUser({
email: 'test#test.com',
password: 'test',
}, history)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
In order to test a successful case for signInUser in file actions/index.js:
export const signInUser = ({ email, password }, history) => async dispatch => {
const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
.catch(({ response: { data } }) => {
...
});
if (res) {
dispatch({ type: AUTH_USER }); // Test verified this
localStorage.setItem('token', res.data.token); // Test mocked this
history.push('/feed'); // Test mocked this
}
}
Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:
const localStorageMock = {
removeItem: jest.fn(),
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
New tools for testing have been introduced since the question was initially answered.
The problem with mocking is that you often test the mock and not the real context of your code, leaving some areas of this context untested.
An improvement over telling axios what promise to return is intercepting http requests via Service Workers.
Service worker is a client-side programmable proxy between your web app and the outside world. So instead of mocking promise resolution it is a more broader solution to mock the proxy server itself, intercepting requests to be tested. Since the interception happens on the network level, your application knows nothing about the mocking.
You can use msw (Mock Service Worker) library to do just that. Here is a short video explaining how it works.
The most basic setup I can think of is this:
1️⃣ set up handlers, which are similar to express.js routing methods;
2️⃣ set up mock server and pass handlers as it’s arguments;
3️⃣ configure tests to so that mock server will intercept our requests;
4️⃣ perform tests;
5️⃣ close mock server.
Say you want to test the following feature:
import axios from "axios";
export const fetchPosts = async () => {
const request = await axios.get("/some/endpoint/");
return {
payload: request,
};
};
Then test could look like this:
import { rest } from "msw";
import { setupServer } from "msw/node";
import fetchPosts from "./somewhere";
// handlers are usually saved in separate file(s) in one destined place of the app,
// so that you don't have to search for them when the endpoints have changed
const handlers = [ 1️⃣
rest.get("/some/endpoint/", (req, res, ctx) =>
res(ctx.json({ message: "success" }))
),
];
const server = setupServer(...handlers); 2️⃣
beforeAll(() => {
server.listen(); 3️⃣
});
describe("fetchPosts", () => {
it("should return 'success' message", async () => {
const resp = await fetchPosts();
expect(resp.payload?.data?.message).toEqual("success"); 4️⃣
});
});
afterAll(() => {
server.close(); 5️⃣
});
The configuration may be different depending on framework you are using. Some general examples for, among others, React (both REST and GraphQL) and Angular can be found on MSW’ repo. A Vue example is provided by VueMastery.
You can also find examples on MSW' recipes page.

Categories

Resources