Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

javascript - Cypress with SystemJS

I am attempting to create some basic tests to try out the new Cypress library. In my test I have cy.visit('http://mywebsite.com'); which is loading an AngularJS app that uses SystemJS.

If I understand Cypress correctly, I shouldn't have to do anything else and it will make sure the page is loaded before running anything else. However this doesn't seem to be working because the page is loaded, but SystemJS is still loading the modules.

How can I get Cypress to wait for all the SystemJS modules to load before running any more tests without using cy.wait(5000)?

EDIT

Thanks to Dwelle this is the solution that works for me. I wrap the initial System.import in a promise that gets resolved once the AngularJS app has been bootstrapped.

window.APP_READY = new Promise(function(resolve, reject) {
    System.import('app').then(function(app) {
        angular.element(document).ready(function() {
            angular.bootstrap(document, ['app']);
            resolve();
        });
    });
});

And then in the test

cy.visit('http://mywebsite.com').its('APP_READY');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not familiar with SystemJS or your app, but if we assume you're doing some asynchronous work on load, you can set up some global property which indicates whether the app is ready or not.

// your main.js
let _appReadyResolver;
window.APP_READY = new Promise( resolve => _appReadyResolver = resolve );

// do some async setup
setTimeout(() => {

    _appReadyResolver();
});

Then, in your tests:

cy.visit("/")
    // by default will wait 4sec for APP_READY prop to exist on
    //  window object (unfortunately I don't know how to increase timeouts
    //  of `cy.its` command)
    // After that, it will wait indefinitely for your promise to resolve
    .its("APP_READY")

That being said --- if you're not doing any async setup in your app, but the main.js is simply being loaded asynchronously and it can take longer than 4sec, then I'd do this:

// index.js
<script>
  SystemJS.import('/js/main.js');
  window.APP_READY = new Promise( resolve => {
    let interval = setInterval(() => {
        if ( window.MAIN_READY ) {
            resolve();
            clearTimeout(interval);
        };
  }, 100 );
</script>

// main.js
window.MAIN_READY = true;

You'll want to strip the APP_READY logic from production build.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...