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);
});
});
Related
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
Here is my code. I want to DRY up this case.
describe("Stored id", () => {
it("ID empty", () => {
// when
const wrapper = mount(SigninPage, options);
const vm = wrapper.vm;
});
it("ID exist", () => {
// when
localStorage.setItem(process.env.VUE_APP_SIGNIN_STORED_USER_ID, STORED_ID);
const wrapper = mount(SigninPage, options);
const vm = wrapper.vm;
});
});
How can I use the beforeEach hook like next using typescript?
I want to use the beforeEach hook. But I can not running test because of tsc. I think it will be possible when variable types is correct.
describe("Stored id", () => {
// problem
let wrapper: VueWrapper<??>;
let vm: ??;
beforeEach(() => {
wrapper = mount(SigninPage);
vm = wrapper.vm;
});
it("ID empty", () => {
// const wrapper = mount(SigninPage, options);
// const vm = wrapper.vm;
});
it("ID exist", () => {
// Should I save it before the wrapper is mounted?
localStorage.setItem(process.env.VUE_APP_SIGNIN_STORED_USER_ID, STORED_ID);
// const wrapper = mount(SigninPage, options);
// const vm = wrapper.vm;
});
});
Self answer. I handled like this.
describe("Header", () => {
// eslint-disable-next-line #typescript-eslint/no-explicit-any
let wrapper: VueWrapper<any>;
const code = "A005930";
const options = { propsData: { code } };
beforeEach(async () => {
wrapper = shallowMount(Header, options);
});
it("should have stored data set", async () => {
const mockQueryParams = { code: "A005930", page: 0, size: 100 };
await store.fetchPriceData(mockQueryParams);
// ...
});
// ...
}
Good day! I have this function of AsyncStorage that gets an item of a token. I used with ApolloClient to process the token but when I test it first, it seems to have an error with what will I get by AsyncStorage function.
export function jwtLogin(data) {
return async dispatch => {
const userData = {
email: data.email,
password: data.password,
};
console.log(userData);
const client = new ApolloClient({
link: new HttpLink({
uri: API_URL,
}),
cache: new InMemoryCache(),
});
client
.mutate({
mutation: loginUser,
variables: {
email: userData.email,
password: userData.password,
},
})
.then(resp => {
console.log(resp.data.tokenCreate);
console.log('Token', resp.data.tokenCreate.token);
if (resp.data.tokenCreate.token !== null) {
saveJWTTokenData(resp.data.tokenCreate.token); //from AsyncStorage save function
async function main() { //function of AsyncStorage
await AsyncStorage.getItem('jwt_token').then(item => {
return item;
});
}
console.log(main()); // returns error
Actions.push('main_loading');
} else {
const errors = resp.data.tokenCreate.errors;
{
errors.map(err => {
Alert.alert('Error.', err.message);
});
}
}
})
.catch(err => {
Alert.alert('Error.', err.message);
});
};
}
For the save storage function:
export const saveJWTTokenData = async jwt_token => AsyncStorage.setItem('jwt_token', jwt_token);
My Error Log Picture
I think your Promise is not handled correctly..
Try to add a catch after your then call like this:
.catch(err => console.log(err))
Or try to use your function like this maybe:
await getData("jwt_token")
.then(data => data)
.then(value => this.setState({ token: value })) // here it is setState but I guess you can also return
.catch(err => console.log("AsyncStorageErr: " + err));
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 })
})
})
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!
});