score:0

since the pubsub.publishsync() operation will trigger mysub event handler that updates the state of the component. make sure you wrap the code that causes react state updates into act(), otherwise, you will get a warning:

warning: an update to app inside a test was not wrapped in act(...).

e.g.

index.jsx:

import react, { usestate, useeffect } from 'react';
import pubsub from 'pubsub-js';

export const app = () => {
  const [data, setdata] = usestate('a');

  const mysub = (msg, pubdata) => {
    setdata(pubdata);
  };

  useeffect(() => {
    const token = pubsub.subscribe('topic', mysub);

    return () => {
      pubsub.unsubscribe(token);
    };
  }, []);

  return <div>{data}</div>;
};

index.test.jsx:

import react from 'react';
import pubsub from 'pubsub-js';
import { mount } from 'enzyme';
import { app } from './';
import { act } from 'react-dom/test-utils';

describe('67422968', () => {
  it('should receive data and update the state', () => {
    const wrapper = mount(<app />);
    expect(wrapper.text()).tobe('a');
    act(() => {
      pubsub.publishsync('topic', 'b');
    });
    expect(wrapper.text()).tobe('b');
  });
});

test result:

 pass  examples/67422968/index.test.tsx (7.254 s)
  67422968
    ✓ should receive data and update the state (28 ms)

-----------|---------|----------|---------|---------|-------------------
file       | % stmts | % branch | % funcs | % lines | uncovered line #s 
-----------|---------|----------|---------|---------|-------------------
all files  |   91.67 |      100 |      75 |   90.91 |                   
 index.tsx |   91.67 |      100 |      75 |   90.91 | 15                
-----------|---------|----------|---------|---------|-------------------
test suites: 1 passed, 1 total
tests:       1 passed, 1 total
snapshots:   0 total
time:        7.902 s, estimated 8 s

package versions:

"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"react": "^16.14.0",
"react-dom": "^16.14.0",
"pubsub-js": "^1.9.3"

Related Query

More Query from same tag