Reputation: 696
I have a simple code which I have written to test.
This is my App.js:
const App: () => React$Node = () => {
function sum(a, b) {
alert(a + b);
return a + b;
}
return (
<>
<Button
title="Sum"
onPress={() => {sum(1,2)}}
/>
);
This is my App-test.js in the __tests__
folder:
import 'react-native';
const sum = require('../App');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
When I run npm test
I get this error TypeError: sum is not a function
. Can anyone help.
Note: When I run it on my android phone it works properly and shows 3 in the alert box.
Upvotes: 2
Views: 213
Reputation: 96
It's because you are importing sum
from your App
file but it is not an exported method the way you wrote it.
You can do something like this:
export const sum = (a, b) => {
alert(a + b);
return a + b;
}
export const App = () => (
<Button
title="Sum"
onPress={() => {sum(1,2)}}
/>
);
And use it like this in your test file:
import { sum } from '../App'
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
It's not particularly linked to React Native since you're only trying to test a specific method, which can be use with any framework.
Upvotes: 1