Jest Mock an Express Middleware - express

I am trying to test the following Express route which uses serveFiles as middleware.
import { serveFiles, setup } from 'swagger-ui-express';
export default (app: Express) => {
app.use('/api-docs/private', serveFiles(yamlFile), setup()
};
I attempted to simply mock the unit test but am getting a res.send is undefined error message
jest.mock('swagger-ui-express', () => ({
setup: jest.fn(),
serveFiles: jest.fn(),
}));
const app = express();
app.use(express.json());
describe('Test Private Route', () => {
beforeAll(() => {
jest.clearAllMocks();
const mockServe = swaggerUi.serveFiles;
(mockServe as jest.Mock).mockImplementation((req, res, next) => {
res.send({ message: 'test private' });
next();
});
swagger(app);
});
it('should retrieve something on private endpoint', async () => {
const resp = await request(app).get('/api-docs/private');
expect(resp.body).toEqual({ message: 'test private' });
});
How can I mock serveFiles so it returns resp.body?

Related

I have followed the documentation but I sent the post image via postman error

I have followed all documentation, token and id are correct, I have checked to send text. it works.
I want to send an image via expressjs and multer, but it doesn't work.
https://www.npmjs.com/package/discord-cloud-database
const multerMiddleware = (req, res, next) => {
const multerStorage = multer.memoryStorage();
return multer({
storage: multerStorage,
}).single("photo");
};
const uploadImageMiddleware = async (req, res, next) => {
try {
const file = req.file;
const image = await discordDatabase.uploadFile(file.buffer, file.originalname, { name: "users" });
req.image = image;
next();
} catch (error) {
next(error);
}
};
const catchAsync = (fn) => {
return (req, res, next) => {
fn(req, res, next).catch(next);
};
};
router.route("/").post(
multerMiddleware,
uploadImageMiddleware,
catchAsync(async (req, res, next) => {
try {
res.status(200).json({
status: "success",
data: {
image: req.image.url,
},
});
} catch (error) {
next(error);
}
})
);
app.listen(3000, () => console.log("server run"));
respon from postman:
respon postman
I want to successfully send an image to discord via postman.

How to test socket io from vue jest?

this is my code from vue.js:
async getUserInformation(user_id){
return await new Promise((resolve, reject) => {
this.$socket.client.emit('getUserInfo', user_id, (err,res) => {
err ? reject(err) : resolve(res)
})
})
},
async selectAction() {
let getReponse= await this.getUserInformation(this.user_id)
this.userInformation = getResponse
}
this is my code from vue jest
describe('editUser.vue', () => {
let wrapper
beforeEach(() => {
wrapper = shallowMount(editUser, {
mixins: [global]
})
});
it('trigger submit button w/o data input from text fields', async () => {
await wrapper.find('[data-testid="get_user_button"]').trigger('click')
});
});
Picture below is the error message I received after I run unit testing

Jest Mocking with Quasar and Typescript

I want to mock Amplify Auth service in my test. There is no error, but test doesn't work because of my mock.
Here is the code I'm about to test:
signIn(): void {
if (!this.valid) return;
this.loading = 1;
this.$Auth
.signIn(this.email, this.password)
.then(() => this.$router.push({ name: "homeManagement" }))
.catch((err: any) => (this.errorMessage = err.message))
.finally(() => (this.loading = 0));
}
Here is the test:
const $t = jest.fn();
$t.mockReturnValue("");
const $Auth = jest.fn();
$Auth.mockReturnValue({
code: "UserNotFoundException",
name: "UserNotFoundException",
message: "User does not exist."
});
const factory = mountFactory(LoginForm, {
mount: {
mocks: {
$Auth
}
}
});
describe("LoginForm", () => {
it("User not found", async () => {
const wrapper = factory();
await wrapper.setData({
email: "david#gmail.com",
password: "Qwer321"
});
await wrapper.vm.signIn();
expect(wrapper.vm.$data.errorMessage.length).not.toEqual(0);
});
});
Figured out a solution, but maybe there is a better one flush-promises to mock Amplify call:
const $Auth = jest.fn();
$Auth.signIn = () => Promise.resolve();
describe("LoginForm", () => {
it("User does not exist", async () => {
const wrapper = factory();
await wrapper.setData({
email: "david#gmail.com",
password: "Qwer321",
valid: true
});
await wrapper.vm.signIn();
await flushPromises();
expect(wrapper.vm.$data.errorMessage.length).not.toEqual(0);
});
});

How to test passport LocalStrategy with jest

Stock with express passport LocalStrategy test, probably on mocking request.
test('should Test password Login auth', async (done) => {
const response = jest.fn((arg)=> console.log('args', arg));
const next = jest.fn();
let mockReq = {body: { username: "test#gmail.com", password: "tets"}}
let mockRes = {send: function(ats){console.log("mockResFunc", ats), response()}};
passport.authenticate('local', ()=> response())(mockReq, mockRes);
expect(next).not.toHaveBeenCalled();
expect(response).toHaveBeenCalled();
but callback is never called as well as i didn't found password and username goes to passport function. Does anyone ideas how to mock credentials using jest(i think here is clue)?
passport.use(new LocalStrategy(
async function(username, password, done) {
const existingUser = await User.findOne({ 'email' : username })
console.log('credits', username, password, existingUser.email)
if (existingUser) {
let validUsr = existingUser.validPassword(password);
if (existingUser && validUsr) {
console.log('passport',existingUser.email)
return done(null, existingUser);
}
}
return done(null, false, { message: 'Wrong credentials.' });
}
));
Dont write a mock function for something like local strategy, write an actual function
const request = require('supertest')
const app = require('../server/app')
describe('Login', () => {
it('should fail with incorrect credentials', async () => {
const res = await request(app)
.post('/auth/login')
.send({
email: 'dummy',
password: 'demo'
})
expect(res.statusCode).toEqual(401)
expect(res.body).toHaveProperty('message')
})
it('should succeed with correct credentials', async () => {
const res = await request(app)
.post('/auth/login')
.send({
email: 'demo',
password: 'demo'
})
expect(res.statusCode).toEqual(200)
expect(res.body).toEqual({ email: 'demo' })
})
})
describe('Logout', () => {
it('should logout successfully', async () => {
const res = await request(app).post('/auth/logout')
expect(res.statusCode).toEqual(200)
expect(res.body).toEqual({ ok: true })
})
})

How to mock axios call within a method?

I am trying to mock an axios call within a vuejs method. Is this possible?
Here is my vue component (SomeObj):
methods:{
callAxiosMethod() {
const callApi= axios.create();
callApi.defaults.timeout = 10000;
callApi.get(mockedUrl)
.then(response => {
console.log('response is ' + response);
})
.catch(e => {});
}
}
Here is my spec.js
let mockData = {};
beforeEach(() => {
jest.spyOn(axios, 'get').mockReturnValue(Promise.resolve(mockData));
});
let wrapper = shallowMount(SomeObj, {
stubs: [], localVue, mocks: {
mockUrl: mockUrl,
$route: {
params: { testId: "123" }
}
}
});
it('is a Vue instance', () => {
expect(wrapper.isVueInstance()).toBeTruthy();
axios.get.mockResolvedValue(mockData);
wrapper.vm.callAxiosMethod();
})
When I looked at the coverage, the system says the callApi is not covered. Any idea on how I can mock the axios call within the function?
Your code calls axios.create so you need to mock that function to return a mock callApi object.
Here is a simplified working example:
code.js
import * as axios from 'axios';
const mockedUrl = 'http://mock-url';
export const callAxiosMethod = () => {
const callApi = axios.create();
callApi.defaults.timeout = 10000;
return callApi.get(mockedUrl); // <= return the Promise so it can be awaited
}
code.test.js
import { callAxiosMethod } from './code';
jest.mock('axios', () => ({
create: jest.fn().mockReturnValue({
defaults: {},
get: jest.fn().mockResolvedValue('mocked data')
})
}));
test('callAxiosMethod', async () => { // <= async test function
const response = await callAxiosMethod(); // <= await the Promise
expect(response).toBe('mocked data'); // Success!
});