jest unit tests failing, setData does not seem to be working - node.js

I'm trying to learn unit testing my vue application with jest by following a tutorial. I set up this component called AppHeader containing a button that is only visible when the variable "loggedIn" is true.
In order to set the value "loggedIn" to true, I use .setData to change its value. Am i using setData incorrectly or is there something else going on?
AppHeader:
<template>
<div>
<button v-show="loggedIn">Logout</button>
</div>
</template>
<script>
export default {
data() {
return {
loggedIn: false,
};
},
};
</script>
AppHeader.spec.js:
import AppHeader from "#/components/AppHeader.vue";
import { mount } from "#vue/test-utils";
describe("AppHeader", () => {
test("hide button when user is logged off", () => {
const wrapper = mount(AppHeader);
expect(wrapper.find("button").isVisible()).toBe(false);
});
test("show button when user is logged in", () => {
const wrapper = mount(AppHeader);
wrapper.setData({ loggedIn: true });
expect(wrapper.find("button").isVisible()).toBe(true);
});
});
output:
FAIL tests/unit/AppHeader.spec.js
AppHeader
√ hide button when user is logged off (23ms)
× show button when user is logged in (7ms)
● AppHeader › show button when user is logged in
expect(received).toBe(expected) // Object.is equality
Expected: true
Received: false
11 | const wrapper = mount(AppHeader);
12 | wrapper.setData({ loggedIn: true });
> 13 | expect(wrapper.find("button").isVisible()).toBe(true);
| ^
14 | });
15 | });
16 |
at Object.<anonymous> (tests/unit/AppHeader.spec.js:13:48)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 2.85s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! music_gym#0.1.0 test:unit: `vue-cli-service test:unit`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the music_gym#0.1.0 test:unit script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\HP\AppData\Roaming\npm-cache\_logs\2021-10-25T10_35_11_082Z-debug.log

I think the issue here may be that you are changing the data but now waiting for the next change detection cycle to trigger, this happens asynchronously.
You can await setData to let these changes settle as the following example (don't forget to set your arrow function as async), also you can further read about this in this link about testing asynchronous components where setData is mentioned as one of the methods that can be awaited and also in setData's documentation.
test("show button when user is logged in", async() => {
const wrapper = mount(AppHeader);
await wrapper.setData({ loggedIn: true });
expect(wrapper.find("button").isVisible()).toBe(true);
});

Related

Mongoose: looks like you're trying to test a Mongoose app with Jest's default jsdom test environment

Can anyone help here. I couldn't run my test file. Below is the error & test file.
jest.useFakeTimers();
import { orderController } from '../controllers/orderController';
import { orderService } from '../service/orderService';
const res: any = {
send(object: any) {
return object;
}
};
describe("Methods in orderController", () => {
test("checking an API", async () => {
const patientDetailsMock = await jest.spyOn(orderService, 'getPatientDetails');
//const req = {}
//await orderController.createOrder(req, res);
expect(patientDetailsMock).toHaveBeenCalled();
//console.log("hello..inside test",patientDetailsMock)
//expect(patientDetailsMock).toBeTruthy();
});
});
>chandanasriharimummaneni#PTRL671:~/Desktop/demo/JestTesting/node-orders$ npm test
> node-orders#0.0.1 test /home/chandanasriharimummaneni/Desktop/demo/JestTesting/node-orders
> jest
FAIL src/test/orderController.test.ts
Methods in orderController
✕ checking an API (3ms)
● Methods in orderController › checking an API
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
21 | //const req = {}
22 | //await orderController.createOrder(req, res);
> 23 | expect(patientDetailsMock).toHaveBeenCalled();
| ^
24 | //console.log("hello..inside test",patientDetailsMock)
25 | //expect(patientDetailsMock).toBeTruthy();
26 |
at Object.<anonymous> (src/test/orderController.test.ts:23:36)
console.warn node_modules/mongoose/lib/helpers/printJestWarning.js:4
Mongoose: looks like you're trying to test a Mongoose app with Jest's default jsdom test environment. Please make sure you read Mongoose's docs on configuring Jest to test Node.js apps: http://mongoosejs.com/docs/jest.html
console.info node_modules/common-component/lpl/utils/logger/logger.js:184
{ uniqId: '', req: '', jsonObject: '', description: '', arguments: '' } [
'AWS-MIS-Config',
'{"provider":"amazon","keyId":"AKIAT5D3HEZTLAOGKVPG","key":"ZrPLIGmGXWh/nPh0euj+042m+yUUJUzUYvwPMoRR","region":"us-east-1"}'
]
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.994s, estimated 2s
Ran all test suites.
Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
What are ways to mock db and methods using mongoose ORM?
Is there any way to mock db connection with object reference ? Also help me to to clear the issue. I have changed jsdom test environment.

When collection is created, the documents are added to it at once

Still learning firestore, i want to write a function which would create multiple documents upon the creation of a collection at once. So i wrote this code to try it out. i saw the code as an answer to something similar.
const fsRef = admin.firestore();
export const moreCreations = functions.firestore
.document(
"dev_env/schools/school_collections/KithAndKin7394/students/{userID}"
)
.onCreate((snap, context) => {
const newSchoolRef = fsRef
.collection("dev_env")
.doc("schools")
.collection("school_collections")
.doc("KithAndKin7394")
.collection("students")
.doc(snap.id);
// Trying something on documents
const documentIds = [
'CRK_IRK',
'PHE',
'agricScience',
'basicScience',
'basicTechnology',
'businessStudies',
'computerStudies',
'creativeArts',
'english',
'frenchLanguage',
'hausaLanguage',
'homeEconomics',
'iboLanguage',
'maths',
'socialStudies',
'yoruba'
];
const batch = fsRef.batch();
const data ={};
const setbatch = documentIds.forEach(docId => {
batch.set(newSchoolRef.collection('JSS1').doc('${docId}'), data);
})
batch. commit().then(response => {
console.log('Success');
}).catch(err => {
console.error(err);
})
});
I am getting these errors:
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions# lint C:\brighterbrains\functions
> tslint --project tsconfig.json
ERROR: C:/brighterbrains/functions/src/index.ts:168:23 - Expression has type `void`. Put it on its own line as a statement.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! functions# lint: `tslint --project tsconfig.json`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the functions# lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\dell\AppData\Roaming\npm-cache\_logs\2020-03-30T02_04_34_455Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code2
What i want is when the collection "JSS1" is created, the documents "documentsId" are added to it at once. The code is from this forum but it is not working. Please can anyone point my mistake and help with me with the corrections? The documentation doesn't do or say anything about such actions.
Thanks in advance.
Remove const setbatch = from before the forEach(). It doesn't have a return value.
I have solved it. Below is the updated code:
export const moreCreations = functions.firestore
.document(
"dev_env/schools/school_collections/KithAndKin7394/students/{userID}"
)
.onCreate((snap, context) => {
const newSchoolRef = fsRef
.collection("dev_env")
.doc("schools")
.collection("school_collections")
.doc("KithAndKin7394")
.collection("students")
.doc(snap.id);
// Trying something on documents
const documentIds = [
'CRK_IRK',
'PHE',
'agricScience',
'basicScience',
'basicTechnology',
'businessStudies',
'computerStudies',
'creativeArts',
'english',
'frenchLanguage',
'hausaLanguage',
'homeEconomics',
'iboLanguage',
'maths',
'socialStudies',
'yoruba'
];
const batch = fsRef.batch();
const data ={};
documentIds.forEach(docId => {
batch.set(newSchoolRef.collection('JSS1').doc(docId), data);
})
batch.commit().then(response => {
console.log('Success');
}).catch(err => {
console.error(err);
})
});
It deployed successfully and upon creation of a document, the collection JSS1 is automatically created with the documents under the documentsId array automatically added.
I wanna thank #samthecodingman for helping me spot the area i need to edit. And #DougStevenson too.

Jest globalTeardown not run after test is failed

I am trying to start and stop serverless application through code. I am able to start and stop it once all tests pass. However when test fails globalTeardown do not run. You can check sample project here: https://github.com/bilalsha/sls-test-jest/tree/fail_test
teardown.js
module.exports = async function() {
let slsOfflineProcess = global.__SERVERD__;
slsOfflineProcess.stdin.write('q\n');
slsOfflineProcess.stdin.pause();
await slsOfflineProcess.kill('SIGINT');
console.log('Serverless Offline stopped');
};
output
7 | expect(res.statusCode).toEqual(200);
> 8 | expect(res.body).toEqual('Go Serverless v1.0! Your function executed successfully!');
| ^
9 | });
10 | });
11 |
at Object.<anonymous> (handler.test.js:8:20)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.972s, estimated 2s
Ran all test suites.
npm ERR! Test failed. See above for more details.
Just eyeballing the docs it looks like your problem is in your jest.config.js when you set it to bail: true
https://github.com/bilalsha/sls-test-jest/blob/fail_test/test/jest.config.js#L3
the docs say that if bail is true it's the same as making the tests stop after the first failure.
https://jestjs.io/docs/en/configuration#bail-number--boolean
I would try changing bail: 0 (the default), and seeing if it produces your expected behavior.
What you can do is add create a script containing the afterAll function:
afterAll(() => {
console.log("I ran");
});
And add the script to the setupFiles or setupFilesAfterEnv. In my case, I ejected one react poc code that had failing tests:
In package.json's Jest config there was this entry:
"jest": {
...
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.js"
],
...
}
So I added the clause in setupTests.js below is the edited file:
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '#testing-library/jest-dom/extend-expect';
afterAll(() => {
console.log("I ran");
});
Now, when I ran my tests this is the result:
FAIL src/App.test.js
✓ renders learn react link (14ms)
✕ renders class (5ms)
● renders class
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
18 | // someClass.someProp = "";
19 | render(<App />);
> 20 | expect(track).toHaveBeenCalledTimes(1);
| ^
21 | });
22 |
at Object.<anonymous> (src/App.test.js:20:17)
console.log src/setupTests.js:8
I ran <---------------
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 1.352s, estimated 2s
Ran all test suites.
You can see that I ran is there even after failing a test. This is an alternative that you may use, as you have put a bounty I thought maybe solving the problem is more important that why globalTeardown is not working.

How to handle gRPC error crashing Node app

I have a simple Express App communicating with another over gRPC, it appears to be crashing on an error event.
events.js:167
throw er; // Unhandled 'error' event
^
Error: 2 UNKNOWN: Stream removed
at Object.exports.createStatusError (/home/justin/singles-api/node_modules/grpc/src/common.js:91:15)
at ClientReadableStream._emitStatusIfDone (/home/justin/singles-api/node_modules/grpc/src/client.js:233:26)
at ClientReadableStream._receiveStatus (/home/justin/singles-api/node_modules/grpc/src/client.js:211:8)
at Object.onReceiveStatus (/home/justin/singles-api/node_modules/grpc/src/client_interceptors.js:1272:15)
at InterceptingListener._callNext (/home/justin/singles-api/node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.onReceiveStatus (/home/justin/singles-api/node_modules/grpc/src/client_interceptors.js:618:8)
at /home/justin/singles-api/node_modules/grpc/src/client_interceptors.js:1029:24
Emitted 'error' event at:
at ClientReadableStream._emitStatusIfDone (/home/justin/singles-api/node_modules/grpc/src/client.js:234:12)
at ClientReadableStream._receiveStatus (/home/justin/singles-api/node_modules/grpc/src/client.js:211:8)
[... lines matching original stack trace ...]
at /home/justin/singles-api/node_modules/grpc/src/client_interceptors.js:1029:24
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! singles-api#0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the singles-api#0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
I'm using some minimal example code for gRPC, how would I go about handling this to prevent the crash? as I'm not quite sure what it is i'm trying to prevent, presumably just a broken/restarting stream?
var lnrpcDescriptor = grpc.load("./rpc.proto");
var lnrpc = lnrpcDescriptor.lnrpc;
var lnd = new lnrpc.Lightning(hostport, credentials);
var call = lnd.subscribeInvoices(request)
call.on('data', function(response) {
if (response.settle_index === '0') {
console.log("New Invoice Issued: " + response.payment_request)
}
else {
//iterate through array to find who paid their invoice and update the db
for (var i = 0; i < loadedDB.db.Node.length; i++) {
if (loadedDB.db.Node[i].add_index == response.add_index) {
console.log("Node " + loadedDB.db.Node[i].Id + " has settled their invoice.");
loadedDB.db.Node[i].isSettled = true;
saveDB.writeEntry();
}
}
}
});
call.on('status', function(status) {
console.log(status);
});
call.on('end', function() {
console.log('subscribeInvoices stream ended')
});

eslint throws error

i am new android beginner and try to deploy firebase functions but show some error how to solve this problem plz help me.
Firebase database structure
User Table
Users
user_id
device_token : user_device_token
Name : user_name
Notification Table
notifications
to_user_id
notification_id
from : from_user_id
Error
Index.js
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
/*
* 'OnWrite' works as 'addValueEventListener' for android. It will fire the function
* everytime there is some item added, removed or changed from the provided 'database.ref'
* 'sendNotification' is the name of the function, which can be changed according to
* your requirement
*/
exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite(event => {
/*
* You can store values as variables from the 'database.ref'
* Just like here, I've done for 'user_id' and 'notification'
*/
const user_id = event.params.user_id;
const notification_id = event.params.notification_id;
console.log('We have a notification from : ', user_id);
/*
* Stops proceeding to the rest of the function if the entry is deleted from database.
* If you want to work with what should happen when an entry is deleted, you can replace the
* line from "return console.log.... "
*/
if(!event.data.val()){
return console.log('A Notification has been deleted from the database : ', notification_id);
}
/*
* 'fromUser' query retreives the ID of the user who sent the notification
*/
const fromUser = admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
console.log('You have new notification from : ', from_user_id);
/*
* The we run two queries at a time using Firebase 'Promise'.
* One to get the name of the user who sent the notification
* another one to get the devicetoken to the device we want to send notification to
*/
const userQuery = admin.database().ref(`/Users/${from_user_id}/Name`).once('value');
const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
return Promise.all([userQuery, deviceToken]).then(result => {
const userName = result[0].val();
const token_id = result[1].val();
/*
* We are creating a 'payload' to create a notification to be sent.
*/
const payload = {
notification: {
title : "New Friend Request",
body: `${userName} has sent you request`,
icon: "default",
}
};
/*
* Then using admin.messaging() we are sending the payload notification to the token_id of
* the device we retreived.
*/
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
});
});
});
});
**cmd show error **
C:\Users\TahirAliAwan\Desktop\Function>firebase deploy
=== Deploying to 'videochat-96f75'...
i deploying functions
Running command: npm --prefix %RESOURCE_DIR% run lint
functions# lint C:\Users\TahirAliAwan\Desktop\Function\functions
eslint .
C:\Users\TahirAliAwan\Desktop\Function\functions\index.js
61:11 warning Avoid nesting promises promise/no-nesting
84:14 warning Avoid nesting promises promise/no-nesting
84:69 error Each then() should return a value or throw promise/always-return
✖ 3 problems (1 error, 2 warnings)
npm ERR! Windows_NT 10.0.10586
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "--prefix" "C:\Users\TahirAliAwan\Desktop\Function\functions" "run" "lint"
npm ERR! node v6.11.5
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! functions# lint: eslint .
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint script 'eslint .'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the functions package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! eslint .
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs functions
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls functions
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! C:\Users\TahirAliAwan\Desktop\Function\npm-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code1
After #PeterHaddad tip and my effort, I solved this problem by removing this line
.then(response => { console.log('This was the notification Feature'); and update nodejs.
Thanks to all.

Resources