Why if i created a mock i am still getting error? - vue.js

i am doing testing, i made a test in that test i create a mock for a fake function
jest.mock('#/services/myService', ()=>({getAvailables: jest.fn().mockReturnValue()}))
that function is running in my component
onMounted(async () => {
const answer = await getAvailables1()
const answer = await getAvailables2()
const answer = await getAvailables3()
but still i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables1) is not a function
(node:81921) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag
if i put like this first getAvailables2
onMounted(async () => {
const answer = await getAvailables2()
const answer = await getAvailables1()
i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables2) is not a function
if i put like this first getAvailables3
onMounted(async () => {
const answer = await getAvailables3()
const answer = await getAvailables2()
i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables3) is not a function
also i try with mockResolvedValue, does not worked
export const getAvailables = async () => {
let response
let error
try {
response = await getData()
} catch (err) {
error = err
throw err
}
return { response, error }
}

It looks like you want a mock partial:
jest.mock('#/services/myService', () => {
const originalModule = jest.requireActual('#/services/myService');
return {
__esModule: true,
...originalModule,
getAvailables1: () => Promise.resolve({ foo: 'bar' }),
getAvailables2: () => Promise.resolve({ foo: 'baz' }),
getAvailables3: () => Promise.resolve({ foo: 'bad' }),
/* any other method of your service that gets called */
};
});
This will mock the provided functions in the mock while the rest of the service will function as in the original.

getAvailables() is async function that always returns a promise.
So, in order to mock that function you need to return the mock promise with success or rejected value.
Following is the example of mocking that function which returns success promise.
jest.mock('#/services/myService', () => ({
getAvailables: jest.fn().mockResolvedValue(true)
}))

Related

promise returned from getRestaurantsFromYelp is ignored

Morning/Evening everybody
So I'm tryna get restaurants from yelpApi(react native App), but the fetch is not working.
First I'm getting a message as what "businesses" isn't a resolved variable, and the response from my getRestaurantsFromYelp() function is getting ignored, don't know why. If anybody could hep me fix that.
const [restaurantsData, setRestaurantsData] = useState(localRestaurants);
const getRestaurantsFromYelp = () => {
const yelpUrl = "api.yelp.com/v3/businesses/search?term=restaurants&location=US"
const apiOptions = {
headers : {
Authorization : `Bearer ${YELP_API_KEY}`,
}
}
return fetch(yelpUrl, apiOptions).then((res) => res.json()).then((json) => setRestaurantsData(json.businesses)); //message => unresolved variable businesses
};
useEffect(() =>{
getRestaurantsFromYelp(); // message => promise returned from getRestaurantsFromYelp is ignored
}, [])

UnhandledPromiseRejection when I am trying to spy window object (jest + nuxt js)

I am using jest to spy window object to define my own window.scrollY value for my nuxt js component.
My jest codes:
const winSpy = jest.spyOn(global, 'window', 'get')
winSpy.mockImplementation(() => ({
scrollY: 200
}))
It works fine, but the error below is shown in terminal:
node:internal/process/promises:265
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: This error originated either by throwing inside of an
async function without a catch block, or by rejecting a promise which was not handled
with .catch(). The promise rejected with the reason "TypeError: Cannot read
properties of undefined (reading 'get')".] {
What is the problem?
Can anyone help me to fix that?
You need to include the original window properties in the mockImplementation:
describe('MyComponent', () => {
it('reads scrollY', () => {
const originalWindow = { ...window }
const windowSpy = jest.spyOn(global, 'window', 'get')
windowSpy.mockImplementation(() => ({
...originalWindow, 👈
scrollY: 200,
}))
const wrapper = shallowMount(MyComponent)
expect(wrapper.vm.top).toBe(200)
})
})
demo

React Native testing cannot read property 'call' of undefined

I have built an application in react native, and am now going through the process of updating some old test suites. The test running an error is a component test using react test renderer to simulate the functionality of the screen.
Error Summary: One of the expect statements is throwing an error saying
Cannot read property 'call' of undefined
When the value exists and I can print out the property call like so
console.log(store.dispatch.mock.calls[6][0]);
and it gives me the expected value.
CODE:
//Imports
jest.spyOn(Date, "now").mockImplementation(() => 1479427200000);
const mockStore = configureStore([]);
describe("block1", () => {
it("test1", async done => {
try {
let component;
let store = mockStore(stores.SummaryR1);
store.dispatch = await jest.fn();
const mockDate = new Date(1466424490000);
const spy = jest.spyOn(global, "Date").mockImplementation(() => mockDate);
Date.now = jest.fn(() => 1466424490000);
await act(async () => {
component = await renderer.create(
<PaperProvider>
<Provider store={store}>
<Receive_Signature />
</Provider>
</PaperProvider>
);
});
const expected = await component.toJSON();
expect(expected).toMatchSnapshot();
await act(async () => {
//action
});
await act(async () => {
//action
});
await act(async () => {
//action
});
await act(async () => {
//action
});
await act(async () => {
//action
});
expect(store.dispatch).toHaveBeenCalledTimes(8);
expect(store.dispatch).toHaveBeenNthCalledWith(1, {results1});
expect(store.dispatch).toHaveBeenNthCalledWith(2, {results2});
expect(store.dispatch).toHaveBeenNthCalledWith(3, {results3});
expect(store.dispatch).toHaveBeenNthCalledWith(4, {results4});
expect(store.dispatch).toHaveBeenNthCalledWith(5, {results5});
expect(store.dispatch).toHaveBeenNthCalledWith(6, {results6});
expect(store.dispatch).toHaveBeenNthCalledWith(7, {results7} );
expect(store.dispatch).toHaveBeenNthCalledWith(8, {results8});
expect(navigateToScreen).toHaveBeenCalledTimes(1);
expect(navigateToScreen.mock.calls[0][0]).toEqual("Processor_Dashboard");
done();
} catch (error) {
done.fail(error);
}
}, 15000);
The error is forming on testing results7 on the 7th call.
Firstly I know there are 8 calls because of
expect(store.dispatch).toHaveBeenCalledTimes(8);
I can then also print out results7, and see that I have the correct data for results7. But when I run it in the jest expect statement I get the error:
Cannot read property 'call' of undefined
I have no idea why there is this error since all the other expects run, and if I comment out just the one statement the rest of the suite runs fine as well. For some reason it is only erroring out on the one expect statement.
Obviously the data has been removed, but does not affect how it would run.

Can't use Vue.js Data in Created ()

I'm wondering if is it possible, how can I use Vue.js data in my Created() function.
I'll show some code so you can see why I say.
data (){
return {
model: {},
foo: 'boo'
}
},
created (){
const getModel = () => {
const modelId = this.$route.params.id
axios.get('/api/model', { params: {modelId: modelId}})
.then(res => {
this.model = res.data
this.boo = 'hello'
console.log(this.model)
console.log(this.foo)
})
.catch(err => console.log(err))
}
getModel()
const init = () =>{
console.log(this.model)
console.log(this.foo)
}
init()
The first console.log(foo) returns 'hello'.
The second one (init) returns 'boo'.
Also the first console.log(this.model) is what I expect to get but once is out of the axios method it's like empty again all over the mounted function.
I've tried a lot of things but none of them worked, hope I get a solution... Thanks in advance!
As soon as JS functions are non-blocking - your axios call isn't done (model is still empty) when you call for init
Define init as components method
Call this.init() in axios.get callback
It might have to do with the fact that in your created hook you're creating a function using the function keyword, which means your init function will have its own context(its own this).
A solution to this problem would be to use an arrow function.
data () { return { foo: 'bar' } }
created () {
const init = () => {
console.log(this.foo);
}
init(); // bar
}
More about arrow functions
UPDATE
Actually, the issue stems from not awaiting for getModel. Because you are making a request, you first need to wait for the promise to resolve, and then use its resolved data in the code that depends on it.
The async/await version would be:
async created () {
const getModel = async () => {
const modelId = this.$route.params.id
try {
const res = await axios.get('/api/model', { params: {modelId: modelId}})
this.model = res.data
this.boo = 'hello'
console.log(this.model)
console.log(this.foo)
} catch (err) {
console.error(err)
}
}
const init = () =>{
console.log(this.model)
console.log(this.foo)
}
// An async function always returns a promise
await getModel();
init();
}

react-native fetch undefined on button press

I have a function when I press a button to get data
however my app is erroring on fetch undefined
async doNext() {
const response = await fetch(`https://facebook.github.io/react-native/movies.json`);
const jsonData = await response.json();
console.log(jsonData);
}
error:
Possible Unhandled Promise Rejection (id: 0)
undefined is not a function evaluating 'fetch'('https://facebook.github.io/react-native/movies.json'))
I also tried to write it like this:
doTest = async () => {
const response = await fetch(`https://facebook.github.io/react-native/movies.json`);
const jsonData = await response.json();
console.log(jsonData);
}
doNext() {
this.doTest();
}
but got the same error
how do I make 'fetch' defined, if I console.log(fetch) I get undefined
found the problem in my code
self = this;
missing let or var, this was in index.android.js this line alone broke everything no warnings appeared for this