I am using an axios interceptor to add authorization token to its header. The interceptor works fine.
//api.js
import { getAccessToken } from "./utils";
const apiInstance = axios.create();
apiInstance.interceptors.request.use((configIns) => {
const token = getAccessToken();
configIns.headers.Authorization = token ? `Bearer ${token}` : "";
return configIns;
});
export { apiInstance };
Here is my test file to test the interceptor.
// api.test.js
import { apiInstance } from "./api"
import {getAccessToken} from "./utils";
describe("request interceptor", () => {
it("API request should add authorization token to header", () => {
const getAccessToken = jest.fn(getAccessToken);
getAccessTokenMock.mockReturnValue("token");
const result = apiInstance.interceptors.request.handlers[0].fulfilled({ headers: {} });
expect(getAccessTokenMock.mock.calls.length).toBe(1);
expect(result.headers).toHaveProperty("Authorization");
});
});
However the getAccessToken function in not getting mocked for some reason inside the interceptor.
The test fails.
That's not how mocks in Jest work. By calling (I assume variable should be getAccessTokenMock, not getAccessToken):
const getAccessTokenMock = jest.fn(getAccessToken);
getAccessTokenMock.mockReturnValue("token");
What you do is: you create new local mock, that when called, would call your getAccessToken function. Then you mock return value. However, your getAccessTokenMock is never called, because it's not the same instance as in your implementation!
What you need to do is mock your actual function getAccessToken from your ./utils file. It can be done, for example, like this:
import { apiInstance } from "./api"
import {getAccessToken} from "./utils";
// Mock here:
jest.mock('./utils', () => ({
getAccessToken: jest.fn(() => 'token')
});
describe("request interceptor", () => {
it("API request should add authorization token to header", () => {
const result = apiInstance.interceptors.request.handlers[0].fulfilled({ headers: {} });
expect(getAccessToken.mock.calls.length).toBe(1);
expect(result.headers).toHaveProperty("Authorization");
});
});
What is happening here is that when file is loaded, jest.mock would run first and would replace your implementation of getAccessToken with the mock - it would be then accessible from both implementation and test (as the same instance), meaning that you can verify if it has been called.
Please find more about mocks here or here. Alternatively you can also use spyOn to achieve similar result (then you don't need jest.mock, but you have to import your getAccessToken function without destructuring).
Related
Is it possible to use global onRequest handler to $fetch with Nuxt3, to add specific data on each request?
With nuxt2 and axios it was simple
/plugins/axios.js
export default function ({ $axios, store, req }) {
$axios.onRequest((config) => {
if (config.data) {
config.data.test = '123';
} else {
config.data = { test: '123' };
}
return config;
});
}
But how achieve same goal on Nuxt3 and $fetch?
Ok, so Nuxt3 $fetch documentation says:
Nuxt uses ofetch to expose globally the $fetch helper...
When we jump into ofetch documentation we can see the Interceptors section. This gives us some options to do what you are trying to achieve. My suggestion is this:
Create a http composable (or anyother name you wish):
// composables/use-http.js
const opts = {
async onRequest({ request, options }) {
// Add your specific data here
options.query = { t: '1234' }
options.headers = { 'Authorization': 'my_token' }
}
}
export default () => $fetch.create(opts)
And here we are making usage of the onRequest interceptor from ofetch
onRequest is called as soon as ofetch is being called, allowing to modify options or just do simple logging.
There you can add any data you want, if you need you can create the logic to pass parameters to this composable and so on...
Now, to actually fetch the data (use the composable):
const http = useHttp() // useHttp is auto-imported
const data = await http('/url') // will trigger the interceptor
I found this question about determine the routes. While the first answer is exactly what I need, and it works
import { Controller, Get, Request } from "#nestjs/common";
import { Request as ExpressRequest, Router } from "express";
#Get()
root(#Request() req: ExpressRequest) {
const router = req.app._router as Router;
return {
routes: router.stack
.map(layer => {
if(layer.route) {
const path = layer.route?.path;
const method = layer.route?.stack[0].method;
return `${method.toUpperCase()} ${path}`
}
})
.filter(item => item !== undefined)
}
}
I want to be able to unit test this.
My end to end test works fine
it('/api (GET) test expected routes', async done => {
const ResponseData = await request(app.getHttpServer())
.get('/api')
.set('Accept', 'application/json');
expect(ResponseData.status).toBe(200);
expect(ResponseData.headers['content-type']).toContain('json');
expect(ResponseData.body.routes.length).toBeGreaterThan(2);
done(); // Call this to finish the test
});
The problem I am having, is how to create and pass the Request part that is needed for the root() call for a unit test. The ExpressRequest is not a class or anything to simply create, and then assign values. It is currently a large definition. I assume there must be an easy way to create one, but I have not found it yet.
You can make use of the #golevelup/ts-jest package to help create mocks of objects. It can take an interface as a generic and return an entire jest mock that is compatible with the type.
I'm mocking expo and the Permissions module, but when calling Permissions.AskAsync Permissions is undefined.
Problem looks like this question. Using Jest to mock named imports
Used the provided answer, but did not work.
I have mocked the axios, which works. Doing the same for the expo module does not work.
The function I want to test:
checkPermission = async () => {
const {statusCamera} = await Permissions.askAsync(Permissions.CAMERA);
// console.log(statusCamera);
this.setState({cameraPermission: statusCamera});
const {statusCameraRoll} = await Permissions.askAsync(Permissions.CAMERA_ROLL);
this.setState({cameraRollPermission: statusCameraRoll});
};
The test:
describe("Test the Permission function", () => {
it('should return rejected permission.', async function () {
const wrapper = shallow(<Photo2/>);
const instance = wrapper.instance();
await instance.checkPermission();
expect(instance.state("cameraPermission")).toBeFalsy();
});
});
The mock I use for expo:
jest.mock('expo', ()=>({
Permissions: {
askAsync: jest.fn()
}
}))
and tried
(In file mocks/expo.js)
export default {
Permissions: {
askAsync: jest.fn(() => {
return "SOMETHING"
})
}
}
and tried
(In file mocks/expo.js)
jest.mock('expo', ()=>({
Permissions: {
askAsync: jest.fn()
}
}));
Error: "TypeError: Cannot read property 'askAsync' of undefined"
This error occures on line where Permissions.askAsyc is called. So Permissions is undefined. (Also checked it with console.log(Permissions)
I expected the instance.state("cameraPermission") to be falsy, but it crashes before it comes to that line.
Since expo change the packages to be import * as Permissions from 'expo-permissions';
You just need to create "mocks/expo-permissions.js" and have it has:
export const getAsync = jest.fn(permissions => Promise.resolve());
export const askAsync = jest.fn(permissions => Promise.resolve());
teerryn's answer is correct and is a good start. To add some more details:
Unless you've configured different roots for Jest, you should place your mock file in __mocks__/expo-permissions.js where __mocks__ is a directory at the same level as your node_modules folder. See Jest docs on mocking node modules.
The permissions argument being passed in will be undefined due to the way we're mocking the module, so you'll need to mock the permission types you want to use. Just need something simple like export const CAMERA_ROLL = 'camera_roll';
If you want to respond differently based on the permission type passed in (for example, allow Permissions.CAMERA but deny Permissions.CAMERA_ROLL and all other types), you can mock the implementation of the askAsync function. For example, your __mocks__/expo-permissions.js file would look like this:
export const CAMERA = 'camera';
export const CAMERA_ROLL = 'camera_roll';
export const askAsync = jest.fn().mockImplementation((permissionType) => {
const responseData = permissionType === CAMERA ? { status: 'granted' } : { status: 'undetermined' }; // you could also pass `denied` instead of `undetermined`
return Promise.resolve(responseData);
});
The problem is that you are handling async tests incorrectly (your checkPermission() function is async). There are several ways you can tell jest that you want to test an async function. Here are a few ways.
Here is a quick solution to your problem:
...
import { Permissions } from 'expo';
...
jest.mock('expo', () => ({
Permissions: {
askAsync: jest.fn(),
}
}));
...
describe("Test the Permission function", () => {
it('should return rejected permission.', () => {
Permissions.askAsync.mockImplementation( permission => { return {status: 'granted'}; } ); // if you want to add some sort of custom functionality
const wrapper = shallow(<Photo2/>);
const instance = wrapper.instance();
return instance.checkPermission().then(data => {
expect(instance.state("cameraPermission")).toBeFalsy();
});
});
});
I am trying to mock an api call using Jest and Vue but I get the error "Expected mock function to have been called with: ... but not called"
I have tried to find a solution but haven't found anything yet.
import DocumentService from "../../src/services/document";
import mockedData from "../__mockData__/documents";
import axios from "axios";
it("should call Document Service and download a document", () => {
let catchFn = jest.fn(),
thenFn = jest.fn();
DocumentService.downloadDocumentById(jwtToken, DocumentURL, id)
.then(thenFn)
.then(catchFn);
// expect(axios.get).toHaveBeenCalledWith(DocumentURL + "/" + id + "/content", {
// headers: { Authorization: "Bearer " + jwtToken, "X-role": "SuperUser" }
// });
expect(axios.get).toHaveBeenCalledWith(DocumentURL);
let responseObj = { data: mockedData };
axios.get.Mockresponse(responseObj);
expect(thenFn).toHaveBeenCalledWith(mockedData);
expect(catchFn).not.toHaveBeenCalled();
});
The test runs synchronously and the expect runs and fails before the Promise callbacks have a chance to run.
Make sure you await the Promise returned by DocumentService.downloadDocumentById to give the callbacks a chance to run:
it("should call Document Service and download a document", async () => { // use an async test function
let catchFn = jest.fn(),
thenFn = jest.fn();
const promise = DocumentService.downloadDocumentById(jwtToken, DocumentURL, id)
.then(thenFn)
.then(catchFn); // remember the Promise
expect(axios.get).toHaveBeenCalledWith(DocumentURL);
let responseObj = { data: mockedData };
axios.get.Mockresponse(responseObj);
await promise; // wait for the Promise
expect(thenFn).toHaveBeenCalledWith(mockedData); // SUCCESS
expect(catchFn).not.toHaveBeenCalled(); // SUCCESS
});
Had the same trouble, made it this way:
import axios from 'axios';
in test axios.get = jest.fn();
expect( axios.get ).toBeCalledWith( yourUrl );
How to test catch from function like this:
getApi () {
const URL = '/api/division?key='
axios.get(URL)
.then((response) => {
this.counter = response.data
})
.catch(err => {
alert(err)
})
}
I'm using axios and vue js with testing JEST. Hope any solution, thanks :')
Try axios-mock-adapter, which can mock the results of axios.get() calls, allowing you to simulate a network error/timeout for a specific request (thus invoking the catch callback in your code):
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
const mock = new MockAdapter(axios);
mock.onGet(`/* URL used by component */`).networkError();
Example unit tests for getApi():
it("does not modify username from network error", async () => {
mock.onGet(`/* URL used by component */`).networkError();
await wrapper.vm.getApi();
expect(wrapper.vm.username).toBe(INIT_USERNAME);
});
it("does not modify username from network timeout", async () => {
mock.onGet(`/* URL used by component */`).timeout();
await wrapper.vm.getApi();
expect(wrapper.vm.username).toBe(INIT_USERNAME);
});
demo