Style a part of the defaultMessage in react-intl - react-intl

I need some way to style a part of the defaultMessage in react-intl, the {Text_to_be_bold} needs to be bold but the rest of the text should stay as it is. Is there any support for that in react-intl or should I manage it manually? Thanks in advance
import { defineMessages } from 'react-intl';
const messagePath = 'some path';
export default defineMessages({
discountMessage: {
defaultMessage:
'{Text_to_be_bold} normal text',
id: `${messagePath}.thisMessage`,
},
});
I read the documentation and expect some proper solution

Related

Ember tests: checkbox

I'm developing ember tests and I want to check if error messages are correctly displayed.
For that I need to check a specific checkbox (or groups of checkboxes) from a list.
Is there a way to specify which checkboxes we want?
Maybe using some kind of parameter that we can pass to choose which we want to select?
Thanks
I figure out how to solve it. I used a collection to identify the elements.
Thanks all for your help!
//products.js
export default create({
main: {
scope: '#main',
allProducts: collection({
itemScope: '.products-list',
item: {
name: text('.card-h1'),
click: clickable('.card-h1'),
color: text('.product-color'),
quantity: text('.product-quantity'),
},
}),
}
});
// products-test.js
function getSingleProduct(name) {
return products.main.allProducts()
.filter(p => p.name.trim() === name).get(0);
}
assert.equal(product.color, 'red');
assert.equal(product.quantity, 10);

How to access Ember Data store when registering test helper? Ember 3.3

I'm using a custom test helper which requires access to the Ember data store, but I don't know how to access it from the given application argument.
export default registerAsyncHelper('myCustomHelper', function(app) {
console.log(app); // how to access store?
let store = app.__registry__.registrations['service:store'];
store.pushPayload(// json payload);
});
How can I get access to the store when registering a custom helper? I've been trying to figure out a way to access it from the __registry__.registrations['service:store'] key but that gives me an undefined value, when I can see that it's there and has the pushPayload function. Help would be greatly appreciated
Hah! I think I got it:
export default registerAsyncHelper('myCustomHelper', function(app) {
let instance = app.buildInstance();
let store = instance.lookup('service:store');
store.pushPayload(// json payload);
});
Not sure if that has any side effects though? Please let me know if it does, I think I've spent enough time trying to setup a good test environment already :p
This is typescript, but it should hopefully work the same in js (without the type annonations though)
// tests/helpers/get-service.ts
import { getContext } from "#ember/test-helpers";
export function getService<T>(name: string): T {
const { owner } = getContext();
const service = owner.lookup(`service:${name}`);
return service;
}
example usage:
// tests/helpers/create-current-user.ts
import { run } from '#ember/runloop';
import { DS } from 'ember-data';
import Identity from 'emberclear/data/models/identity/model';
import { getService } from './get-service';
export async function createCurrentUser(): Promise<Identity> {
const store = getService<DS.Store>('store');
const record = store.createRecord('identity', {
id: 'me', name: 'Test User'
});
await record.save();
return record;
}
this code is from https://emberclear.io
https://gitlab.com/NullVoxPopuli/emberclear/tree/master/packages/frontend/tests/helpers
hope this helps :)

How to set or test this.$parent in Vuejs unit testing?

In my component set
data(){
categories: this.$parent.categories => which I set in main.js
}
Code file main.js
import categories from '../config/categories';
new Vue({
router,
data: {
categories: categories
}
});
I created 1 function unit test
it(‘check component is a button’,() => {
const wrapper = shallow(FormSearch);
expect(wrapper.contains(‘button’)).toBe(true);
});
I run test then show error: Error in data(): "TypeError: Cannot read property ‘categories’ of undefined"
How to fix it. Help me.
Why not import you categories config file directly into your component?
import Categories from '../config/categories'
then your data method can directly access it:
data () { return { categories: Categories }}
You'll find that much easier to test
yes, thanks you. I changed. I run test then it happens error other
Cannot find module '../../config/categories' from 'mycomponet.vue'.
Although. I run project on browser just working well.
How to fix it. Thanks you very much
For Testing , you can set mock data to escape undefined error while testing . But it is not standard solution .....
it(‘check component is a button’,() => {
const wrapper = shallow(FormSearch);
let mockCategories = { // mock category data }
wrapper.$parent = {
categories: mockCategories
}
expect(wrapper.contains(‘button’)).toBe(true);
});
Try this approach:
const Parent = {
data: () => ({
val: true
}),
template: '<div />'
}
const wrapper = shallowMount(TestComponent, {
parent: Parent
})

How to add locale data dynamically using React Intl?

Am using React-intl for internationalization of an UI Util Library. The library has a folder say i18n wherein I place json files for different locales.If the user of this library want to add support for additional locales, he/she can place additional json file with key/value pairs for the respective locale.
But React-intl requires to import and addLocaleData for the respective locale in prior.For example,
import fr from 'react-intl/locale-data/fr';
addLocaleData([...fr]);
Is there a way to addLocaleData and import the locale library for the respective locale dynamically in React-intl?
If you are using webpack. You can code-split the different locale data from your app and load dynamically. Webpack 1 supports only require.ensure() and webpack 2 also supports System.import(). System.import returns a promise while require.ensure uses a callback. https://webpack.github.io/docs/code-splitting.html
With System.import()
import { addLocaleData } from 'react-intl';
const reactIntlLocaleData = {
fr: () => System.import('react-intl/locale-data/fr'),
en: () => System.import('react-intl/locale-data/en')
};
function loadLocaleData(locale){
reactIntlLocaleData[locale]()
.then((intlData) => {
addLocaleData(intlData)
}
}
With require.ensure()
import { addLocaleData } from 'react-intl';
const reactIntlLocaleData = {
fr: () => require.ensure([], (require) => {
const frData = require('react-intl/locale-data/fr');
addLocaleData(frData);
}),
en: () => require.ensure([], (require) => {
const enData = require('react-intl/locale-data/en');
addLocaleData(enData);
})
};
function loadLocaleData(locale){
reactIntlLocaleData[locale]();
}
Depending on your development environment the code above may or may not work. It assumes you are using Webpack2 along with Babel to transpile your code.
Hey I have done this now, as described below and its working :-)
const possibleLocale = navigator.language.split('-')[0] || 'en';
addLocaleData(require(`react-intl/locale-data/${possibleLocale}`));
Here, the locale is fetched from the browser through navigator.language.
Hope this helps :-)

How to access complex nested json in ember.js

after thorough searching stackoverflow and reading through all of the documetation on emberjs.com I'm finding myself stuck. I have a complex json object that I'm trying to model and output in my ember project.
I don't have control over the JSON, otherwise I'd change it's format to be easier digested. That said, here is my problem.
I have the following json
[
{
"id":1,
"catId": "10051",
"catUrl": "path/to/location",
"childCount": "4",
"description": [{
"text": "Description Text"
}],
"identifier": "UNQ123456",
"partialResults": "false"
}
]
What I'm trying to get at is the text value in description. I've tried creating the hasMany and belongsTo nested model construct described on emberjs.com, as well as many other patterns that were described as answers here on stack overflow, yet none of them seem to work or match the data construct I have to work with.
I've even tried the anonymous function in the first block of code on this page. http://emberjs.com/guides/models/defining-models/ trying to traverse this to the text that I want.
Regardless, any help would be much appreciated.
You could define a custom data transform to handle your special JSON field. This can be done by using the DS.RESTAdapter.registerTransform function. Something like this should work for your use case:
DS.RESTAdapter.registerTransform('descriptionText', {
serialize: function(data) {
var text = data[0].text;
return text;
},
deserialize: function(text) {
var data = [Ember.create({text: text})];
return data;
}
});
And then use it as a custom attribute for your model:
App.MyModel = DS.Model.extend({
...
description: DS.attr('descriptionText')
});
Note that the name of the transform could be something else as descriptionText as long you use the same name for DS.attr(...).
Hope it helps.