I have below code snippet which is not covered in jest test coverage. Can someone please help to cover those lines in jest test.
const map = useMap();
const locationClick(): void => { map.locate().on("location found", function (e) {
setP(e.lating); map.flyTo(e.lating, 10.3);
const radius = e.accuracy;
map.setzoom (14.3);
const circle L.circle(e.lating, radius); circle.addTo(map); =
});
};
Related
so I'm experimenting with the LOD object in Three.js however I'm having trouble getting it to work. The code that i am using (excluding some standard setup code like creating a scene etc.) is shown here:
let treeHighDetail = new THREE.Object3D();
let treeLowDetail = new THREE.Object3D();
const gltfLoader = new GLTFLoader();
gltfLoader.load('./resources/low_poly_tree.glb', (gltf) => {
console.log(gltf)
treeLowDetail.add(gltf.scene);
treeLowDetail.traverse(c => {
c.castShadow = true;
})
})
gltfLoader.load('./resources/tree.glb', (gltf) => {
console.log(gltf)
treeHighDetail.add(gltf.scene);
treeHighDetail.traverse(c => {
c.castShadow = true;
})
})
const lod = new THREE.LOD();
let treeMesh = treeHighDetail.clone();
lod.addLevel(treeMesh, 5);
treeMesh = treeLowDetail.clone();
lod.addLevel(treeMesh, 20);
scene.add(lod);
I have two tree models, one low poly and one relatively high. I am attempting to have the high poly tree be displayed when i am close to the object, and the low poly tree render when i am further away from it. Running this code doesn't produce any errors in the console, however none of the models are rendered into the scene at any distance. Any ideas on what the issue could be would be greatly appreciated.
You are accessing the glTF asset before they have been loaded. The above load() method calls are asynchronously so you have to wait for their completion.
There are different ways to achieve this. You could create an instance of THREE.LoadingManager, use it as an argument for GLTFLoader's constructor call and then use its onLoad() callback for creating the LODs.
Or you rewrite your code to use the async/await pattern which is probably the more elegant solution. It would look like so:
const gltfLoader = new GLTFLoader();
const [ gltfLowDetail, gltfHighDetail ] = await Promise.all( [
gltfLoader.loadAsync( './resources/low_poly_tree.glb' ),
gltfLoader.loadAsync( './resources/tree.glb' ),
] );
const treeLowDetail = new THREE.Object3D();
const treeHighDetail = new THREE.Object3D();
treeLowDetail.add(gltfLowDetail.scene);
treeLowDetail.traverse(c => {
c.castShadow = true;
})
treeHighDetail.add(gltfHighDetail.scene);
treeHighDetail.traverse(c => {
c.castShadow = true;
})
const lod = new THREE.LOD();
let treeMesh = treeHighDetail.clone();
lod.addLevel(treeMesh, 5);
treeMesh = treeLowDetail.clone();
lod.addLevel(treeMesh, 20);
scene.add(lod);
You have to ensure the function/method holding this code is async as well.
Could u have a look? no map appeared
https://codepen.io/DeanWinchester88/pen/BaZYewv
async function chart() {
const [data,geo] = await Promise.all([
d3.json(promises[0]),
d3.json(promises[1])
])
console.log("data",data)
console.log("geo", geo)
}
chart()
let path = d3.geoPath()
function ready(error,data,geo){
//topojson object
let topoobject = topojson.feature(geo, geo.objects.counties);
let counties = topoobject.features;
You need to pass the data to the ready function. Right now in your code, the ready function is never called. You can do it like this:
Promise.all([
d3.json(EDUCATION),
d3.json(COUNTIES),
]).then(([data, geo]) => {
ready(null, data, geo);
});
Also, there is a mistake in the EDUCATION url. It should be:
const EDUCATION = "https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/for_user_education.json";
const COUNTIES = "https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/counties.json";
Lastly, the first line of ready misspells topojson.
anyone here implemented Dialog flow fullfilment on graphql server? How do you handle it? Do you handle fulfillment as a mutation or you implement it as a separate rest endpoint?
I am able to expose my local server using ngrok but I am not sure how to go about setting up the fulfillment. I had separated my DF code from GraphQL code such that the DF module only exposes the methods that handle event and text queries to Dialog flow:
// df/index.js
module.exports={
text: ()=>{
self=module.exports
// ...
return self.getResult()
},
event: ()=>{
self=module.exports
// ...
return self.getResult()
},
getResult:()=>{
//...
return{
query,
response,
cards,
quickReply
}
}
}
Then this is passed through the graphQL context and exposed to the bot.resolver.js module where respective mutations for handling text and events are defined as shown
// schema/resolvers/bot.resolver.js
module.exports={
// Mutation
Mutation:{
sendText: (parent,args,context) => {
const {df}=context;
const response = df.text(args);
return response;
},
sendEvent: (parent,args,context) => {
const {df}=context;
const response = df.event(args);
return response;
},
},
};
The corresponding graphQL types are defined in bot.type.js as shown:
const { gql } = require('apollo-server-express');
module.exports=gql`
type Course {
id:ID
header:String!
image:String!
description:String
price:String!
}
type Option {
value:String!
payload:String
link:String
}
type QuickReply {
text:String!
options:[Option!]!
}
type Bot {
query:String!,
response:String!
cards:[Course!]
quickReply:QuickReply
}
type Mutation {
sendText(text: String!, userId:String!, parameters:String): Bot!
sendEvent(name: String!, userId:String!, parameters:String): Bot!
}
`;
Please advise where I can write the code below that sets up dialog flow fulfillment
dialogflow-fulfillment setup code
😊Surprisingly it was as simple as writing it as a middleware on my graphQl api.
// import the required dependencies
const express = require('express');
const bodyParser = require('body-parser')
const cors = require('cors');
const { ApolloServer, } = require('apollo-server-express');
// do not forget your graphQl schema definition
const schema = require('./schema');
// we shall also need to import the data source.
// I will assume an array for our data source defined as below
const models ={
Course:[
{id:1, name:'Chatbots',}
{id:2, name:'React',}
{id:3, name:'Express',}
{id:4, name:'GraphQl',}
],
Book:[
{id:1, title:'Fundermentals in Chatbots',courseId:1},
{id:2, title:'Express for Newbies',courseId:3},
{id:3, title:'Advanced AI on Bots',courseId:1},
{id:4, title:'GraphQl Simplified',courseId:4},
]
}
// Import the WebhookClient class
const { WebhookClient } = require('dialogflow-fulfillment');
// Do the graphQl gymnastics ... I find Apollo server 2 just on point.
const server = new ApolloServer(schema);
const path='/'
const port = process.env.PORT || 4000
const app = express(); // we will merge express with the Apollo server 2
// do the express gymnastics ...
app.use(path,cors(),bodyParser.json(),)
// **IT'S HERE THAT WE DEFINE DIALOG FLOW'S WEB-HOOK AS A MIDDLEWARE**
app.use('/webhook', async (request,response,next)=>{
const agent = new WebhookClient({ request, response });
const {parameters}=request.body.queryResult;
const course =parameters['course'];
// ... do the database logic here ...
// eg get the title of available text books for the particular course
// I will assume
const {id} = await models.Course.find(({name})=>name ===course)
const books = await model.Book.filter(({courseId})=>courseId===id)
const booksTitleArray = books.map(({title})=>title)
let titleList = booksTitle.Array.toString();
titleList.replace(',', ' , ') // put space btn comas
titleList.replace(/\,(?=[^,]*$)/, "and")
let intentMap = new Map();
const recommendBooks courses=>{
agent.add(`For ${course}, We use the following books: ${titleList}`);
};
intentMap.set('course.recommended.books',recommendBooks);
agent.handleRequest(intentMap);
next();
})
server.applyMiddleware({ app, path });
app.listen(port,()=>{
console.log( `Apollo Server Running on http://localhost:${port}`)
})
I feel like writing an article on this because I tried looking for help almost everywhere in vain. Incase I get the time to do so, I will provide it in the comments.😏😉🤔🤭
Guys, we should not forget the ngrok magic if we are testing from localhost 😁
I have a simple saga of this form:
const getAccountDetails = function * () {
const { url } = yield select(state => state.appConfig)
const accountDetails = yield call(apiFetchAccountDetails, url)
}
I'm trying to write a unit test:
describe('getAccountDetails', () => {
const iterator = getAccountDetails()
it("should yield an Effect 'select(state=> state.appConfig)'", () => {
const effect = iterator.next().value
const expected = select(state => state.appConfig)
expect(effect).to.deep.eql(expected)
})
This test fails. Although effect and expected are very similar, they are not identical.
At least one of the differences is buried in payload.selector.scopes, where the yielded effect and expected are as follows:
As the scopes of these two will always be different, how can these tests ever be made to work?
eta: this pattern is adapted from the example linked to from the redux-saga docs
Cracked it after finding this issue from way back.
The fix is to create a named function to do the select and export it from the module where the saga under test lives, and then use this same function in tests. All is well.
export const selectAppConfig = state => state.appConfig
const getAccountDetails = function * () {
const { url } = yield select(selectAppConfig)
const accountDetails = yield call(apiFetchAccountDetails, url)
}
import {selectAppConfig} from './sagaToTest'
describe('getAccountDetails', () => {
const iterator = getAccountDetails()
it("should yield an Effect 'select(state=> state.appConfig)'", () => {
const effect = iterator.next().value
const expected = select(selectAppConfig)
expect(effect).to.deep.eql(expected)
})
I am trying to write a minimum working example of chai-as-promised in order to understand how it is working when testing functions that return a promise.
I have the following function:
simple.test = async (input) => {
return input;
};
and the following test function:
chai.use(sinonChai);
chai.use(chaiAsPromised);
const { expect } = chai;
const should = chai.should();
describe('#Test', () => {
it('test', () => {
expect(simple.test(1)).should.eventually.equal(1);
});
});
However, testing this results in the test not passing, but in a very long error, which is pasted here: https://pastebin.com/fppecStx
Question: Is there something wrong about the code, or what seems to be the problem here?
First: Your mixing expect and should. If you want to use should for assertion, you don't need expect.
Second: To tell mocha that a test is async you have to either call done, return a Promise or use async/await.
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const sinonChai = require('sinon-chai');
const should = chai.should();
chai.use(sinonChai);
chai.use(chaiAsPromised);
// Function to test
const simple = {
test: async (input) => {
return input;
}
}
// Test
describe('#Test', () => {
it('test', () => {
return simple.test(1).should.eventually.equal(1);
});
});