How to load a file into an Angular Test? - http

i'm trying to test an extension validator using Karma and Jasmine with latest Angular version. I have a service that receives a File and checks its extension and MIME type, this is the method signature:
public validateFileType(file: File, validTypes: string[]): Observable<boolean>
As you can see the method receives a File, so i want to either load some files i have in a /testing folder or create a file with '.doc'/'.xls'/'.pdf' extension (i would like to use the first approach, already tried creating a .doc, .xls file and the signature numbers does not match any real file).
But its impossible to load any File as the HttpClient can not be instantiated in a Karma test, i have tried everything i know and searched a lot, any help is really appreciated.
Example
import { TestBed } from '#angular/core/testing';
import { FileValidatorService } from './file-validator.service';
describe('FileValidatorService', () => {
let service: FileValidatorService;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [FileValidatorService] });
service = TestBed.get(FileValidatorService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
describe('Types', () => {
it('should be false', () => {
const content = 'Hello test';
const data = new Blob([content], { type: 'application/zip' });
const arrayOfBlob = new Array<Blob>();
arrayOfBlob.push(data);
const applicationZip = new File(arrayOfBlob, 'Mock.zip', { type: 'application/zip' });
service.validateFileType(applicationZip, ['.doc', '.xls']).subscribe((result: boolean) => {
expect(result).toBeFalsy();
});
});
});
});
This test only works because the file i created generates some random signature code that i don't use so its not recognized and it doesn't match the expected types so is not working as it should.

Related

How to use runtime config in composable?

I want to do this
composables/apiFetch.ts
import { $fetch } from 'ohmyfetch'
export const useApiFetch = $fetch.create({ baseURL: useRuntimeConfig().apiUrl })
And use it within Pinia so I don't repeat myself writing $fetch.create over and over again for every single API call.
somewhere_in_pinia.ts
...TRIM...
actions: {
async doSomething(payload: SomeNicePayload): Promise<void> {
const response = await useApiFetch('/something', { method: 'POST', body: payload })
}
}
...TRIM...
But Nuxt won't allow me
[nuxt] [request error] nuxt instance unavailable
at useNuxtApp (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:472:13)
at Module.useRuntimeConfig (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:480:10)
at $id_Yl353ZXbaH (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:38358:90)
at async __instantiateModule__ (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:40864:3)
I have been looking for solution online, followed instruction from the official discussion to no avail.
EDIT
I don't want to use Nitro, since my backend is already written on Laravel. I need to access the host without re-typing it all over the place so I thought I could use .env and runtimeConfig.
you are trying to access Nuxt instance while it's not ready yet. To make it work, write your composable as a function :
import { $fetch } from 'ohmyfetch'
export const useApiFetch = (url, params) => {
const instance = $fetch.create({ baseURL: useRuntimeConfig().apiUrl })
return instance(url, params)
}

Embed current build time into humans.txt file with nextjs

Placing a humans.txt file into nextjs' /public folder works fine for a static file.
However I'd like to annotate the file with the date of the latest page build (when next build is called). So I created pages/humans.txt.tsx which renders a string that also contains the build time static date:
export default function Test({ buildTime }) {
return `Hello ${buildTime}`
}
export async function getStaticProps() {
return {
props: {
buildTime: new Date().toISOString()
}
}
}
I tried to customize pages/_document.js but even with everything stripped down (for testing) it still renders the doctype and one div with my text in it.
class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
ctx.renderPage = (props) => {
return {
html: "text",
head: null,
}
}
// Run the parent `getInitialProps`, it now includes the custom `renderPage`
const initialProps = await Document.getInitialProps(ctx)
return initialProps
}
render() {
return <Main/>
}
}
Output:
<!DOCTYPE html><div id="__next">text</div>
Returning just string from my documents render instead of <Main/> still renders the doctype and also causes a warning, since render should return an Element.
So I am out of ideas and might resort to using a prebuild script in package.json prebuild: sed ./pages/humans.txt... to replace a marker in the file with the system date and pipe it to public/humans.txt.
Here is an interesting runtime alternative:
Rewriting /humans.txt to /api/humans
You can use the following rule:
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/humans.txt',
destination: '/api/humans',
},
]
},
}
Check the Rewrites docs here
Writing /api/humans
Now you can use any response in your API. However, make sure you are caching it:
// /pages/api/humans.js
export default function handler(req, res) {
res.setHeader('Cache-control', 's-maxage=6000, stale-while-revalidate=30')
res.setHeader('Content-type', 'text/plain')
res.status(200).end('example')
}
Check the API routes docs here

Next.js returns 500: internal server error in Production

Created a next.js full stack application. After production build when I run next start it returns 500 : internal server. I'm using environment varibles for hitting api.
env.development file
BASE_URL=http://localhost:3000
It was working fine in development
service.ts
import axios from 'axios';
const axiosDefaultConfig = {
baseURL: process.env.BASE_URL, // is this line reason for error?
headers: {
'Access-Control-Allow-Origin': '*'
}
};
const axio = axios.create(axiosDefaultConfig);
export class Steam {
static getGames = async () => {
return await axio.get('/api/getAppList');
};
}
Do you have a next.config.js file?
To add runtime configuration to your app open next.config.js and add the publicRuntimeConfig and serverRuntimeConfig configs:
module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}
To get access to the runtime configs in your app use next/config, like so:
import getConfig from 'next/config'
// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// Will only be available on the server-side
console.log(serverRuntimeConfig.mySecret)
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.staticFolder)
function MyImage() {
return (
<div>
<img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
</div>
)
}
export default MyImage
I hope this helps.
I dont think you have setup env.
You need to configure it for it to work. Try it without it and it should work fine!

jsreport 2.0 BeforeRender Not Working

I am working on jsreport v2.0 and wants to render the data for the report. I am using handlebars and phantom-pdf and my beforeRender function is not getting called by default.
For jsreport v2.0, i have added the listener for the beforeRender as following but still it did not seem to be called by default to render the data.
function beforeRenderListeners1(req,res){
console.log("Listener Called");
}
const jsreport = require('jsreport-core')({
})
jsreport.beforeRenderListeners.add('beforeRenderListeners1', (req, res) => {
console.log("hello");
req.data.check = abc();
})
since i don't know the complete code that you are using i will go ahead and provide you a snippet that works in latest jsreport-core v2 (2.0.3) with node 8
const jsreport = require('jsreport-core')()
jsreport.use(require('jsreport-handlebars')())
jsreport.beforeRenderListeners.add('beforeRenderListeners1', (req, res) => {
console.log("before render called")
req.data = req.data || {}
req.data.check = 'check pass'
})
jsreport.init().then(() => {
console.log('started')
return jsreport.render({
template: {
content: '<p>sample demo content, check: {{check}}</p>',
engine: 'handlebars',
recipe: 'html'
}
})
}).then((res) => {
console.log('render done')
console.log(res.content.toString())
}).catch((err) => console.error(err))
put that in a file and then run it, you will see the message before render called being printed in console.

Not able to find Restivus after having added with meteor add nimble:restivus

I have a functioning Angular2-Meteor installation.
On top of this, I have installed Restivus via the command
meteor add nimble:restivus
The installation does not show any problem.
Following the example found on the Restivus page (https://github.com/kahmali/meteor-restivus) I have created the first file (logs.collection.ts) to configure the API
import {Mongo} from 'meteor/mongo';
import {Restivus} from 'meteor/numble:restivus';
import {Log} from '../interfaces/log.interface';
export const Logs = new Mongo.Collection<Log>('logs');
function loggedIn() {
return !!Meteor.user();
}
let allowInsert = () => {return false};
let allowUpdate = () => {return false};
let allowDelete = () => {return false}
Logs.allow({
insert: allowInsert,
update: allowUpdate,
remove: allowDelete
});
if (Meteor.isServer) {
// Global API configuration
var Api = new Restivus({
useDefaultAuth: true,
prettyJson: true
});
// Generates: GET, POST on /api/items and GET, PUT, DELETE on
// /api/items/:id for the Items collection
Api.addCollection(Logs);
}
My problem is that the IDE is telling me that it 'cannot find module meteor/numble:restivus'
Any idea about what I have done wrong?
Thanks in advance
To use Restivus, you don't import it as a module, you simply need to call new Restivus(options). Restivus is only available in server code, so make sure you're in a if (Meteor.isServer) {} block or in a file under a /server directory.

Resources